SemaChecking.cpp 225 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112
  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/Sema/Initialization.h"
  15. #include "clang/Sema/Sema.h"
  16. #include "clang/Sema/SemaInternal.h"
  17. #include "clang/Sema/Initialization.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/ScopeInfo.h"
  20. #include "clang/Analysis/Analyses/FormatString.h"
  21. #include "clang/AST/ASTContext.h"
  22. #include "clang/AST/CharUnits.h"
  23. #include "clang/AST/DeclCXX.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/Expr.h"
  26. #include "clang/AST/ExprCXX.h"
  27. #include "clang/AST/ExprObjC.h"
  28. #include "clang/AST/EvaluatedExprVisitor.h"
  29. #include "clang/AST/DeclObjC.h"
  30. #include "clang/AST/StmtCXX.h"
  31. #include "clang/AST/StmtObjC.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "llvm/ADT/BitVector.h"
  34. #include "llvm/ADT/SmallString.h"
  35. #include "llvm/ADT/STLExtras.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include "clang/Basic/TargetBuiltins.h"
  38. #include "clang/Basic/TargetInfo.h"
  39. #include "clang/Basic/ConvertUTF.h"
  40. #include <limits>
  41. using namespace clang;
  42. using namespace sema;
  43. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  44. unsigned ByteNo) const {
  45. return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
  46. PP.getLangOpts(), PP.getTargetInfo());
  47. }
  48. /// Checks that a call expression's argument count is the desired number.
  49. /// This is useful when doing custom type-checking. Returns true on error.
  50. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  51. unsigned argCount = call->getNumArgs();
  52. if (argCount == desiredArgCount) return false;
  53. if (argCount < desiredArgCount)
  54. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  55. << 0 /*function call*/ << desiredArgCount << argCount
  56. << call->getSourceRange();
  57. // Highlight all the excess arguments.
  58. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  59. call->getArg(argCount - 1)->getLocEnd());
  60. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  61. << 0 /*function call*/ << desiredArgCount << argCount
  62. << call->getArg(1)->getSourceRange();
  63. }
  64. /// Check that the first argument to __builtin_annotation is an integer
  65. /// and the second argument is a non-wide string literal.
  66. static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
  67. if (checkArgCount(S, TheCall, 2))
  68. return true;
  69. // First argument should be an integer.
  70. Expr *ValArg = TheCall->getArg(0);
  71. QualType Ty = ValArg->getType();
  72. if (!Ty->isIntegerType()) {
  73. S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
  74. << ValArg->getSourceRange();
  75. return true;
  76. }
  77. // Second argument should be a constant string.
  78. Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
  79. StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
  80. if (!Literal || !Literal->isAscii()) {
  81. S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
  82. << StrArg->getSourceRange();
  83. return true;
  84. }
  85. TheCall->setType(Ty);
  86. return false;
  87. }
  88. ExprResult
  89. Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  90. ExprResult TheCallResult(Owned(TheCall));
  91. // Find out if any arguments are required to be integer constant expressions.
  92. unsigned ICEArguments = 0;
  93. ASTContext::GetBuiltinTypeError Error;
  94. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  95. if (Error != ASTContext::GE_None)
  96. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  97. // If any arguments are required to be ICE's, check and diagnose.
  98. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  99. // Skip arguments not required to be ICE's.
  100. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  101. llvm::APSInt Result;
  102. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  103. return true;
  104. ICEArguments &= ~(1 << ArgNo);
  105. }
  106. switch (BuiltinID) {
  107. case Builtin::BI__builtin___CFStringMakeConstantString:
  108. assert(TheCall->getNumArgs() == 1 &&
  109. "Wrong # arguments to builtin CFStringMakeConstantString");
  110. if (CheckObjCString(TheCall->getArg(0)))
  111. return ExprError();
  112. break;
  113. case Builtin::BI__builtin_stdarg_start:
  114. case Builtin::BI__builtin_va_start:
  115. if (SemaBuiltinVAStart(TheCall))
  116. return ExprError();
  117. break;
  118. case Builtin::BI__builtin_isgreater:
  119. case Builtin::BI__builtin_isgreaterequal:
  120. case Builtin::BI__builtin_isless:
  121. case Builtin::BI__builtin_islessequal:
  122. case Builtin::BI__builtin_islessgreater:
  123. case Builtin::BI__builtin_isunordered:
  124. if (SemaBuiltinUnorderedCompare(TheCall))
  125. return ExprError();
  126. break;
  127. case Builtin::BI__builtin_fpclassify:
  128. if (SemaBuiltinFPClassification(TheCall, 6))
  129. return ExprError();
  130. break;
  131. case Builtin::BI__builtin_isfinite:
  132. case Builtin::BI__builtin_isinf:
  133. case Builtin::BI__builtin_isinf_sign:
  134. case Builtin::BI__builtin_isnan:
  135. case Builtin::BI__builtin_isnormal:
  136. if (SemaBuiltinFPClassification(TheCall, 1))
  137. return ExprError();
  138. break;
  139. case Builtin::BI__builtin_shufflevector:
  140. return SemaBuiltinShuffleVector(TheCall);
  141. // TheCall will be freed by the smart pointer here, but that's fine, since
  142. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  143. case Builtin::BI__builtin_prefetch:
  144. if (SemaBuiltinPrefetch(TheCall))
  145. return ExprError();
  146. break;
  147. case Builtin::BI__builtin_object_size:
  148. if (SemaBuiltinObjectSize(TheCall))
  149. return ExprError();
  150. break;
  151. case Builtin::BI__builtin_longjmp:
  152. if (SemaBuiltinLongjmp(TheCall))
  153. return ExprError();
  154. break;
  155. case Builtin::BI__builtin_classify_type:
  156. if (checkArgCount(*this, TheCall, 1)) return true;
  157. TheCall->setType(Context.IntTy);
  158. break;
  159. case Builtin::BI__builtin_constant_p:
  160. if (checkArgCount(*this, TheCall, 1)) return true;
  161. TheCall->setType(Context.IntTy);
  162. break;
  163. case Builtin::BI__sync_fetch_and_add:
  164. case Builtin::BI__sync_fetch_and_add_1:
  165. case Builtin::BI__sync_fetch_and_add_2:
  166. case Builtin::BI__sync_fetch_and_add_4:
  167. case Builtin::BI__sync_fetch_and_add_8:
  168. case Builtin::BI__sync_fetch_and_add_16:
  169. case Builtin::BI__sync_fetch_and_sub:
  170. case Builtin::BI__sync_fetch_and_sub_1:
  171. case Builtin::BI__sync_fetch_and_sub_2:
  172. case Builtin::BI__sync_fetch_and_sub_4:
  173. case Builtin::BI__sync_fetch_and_sub_8:
  174. case Builtin::BI__sync_fetch_and_sub_16:
  175. case Builtin::BI__sync_fetch_and_or:
  176. case Builtin::BI__sync_fetch_and_or_1:
  177. case Builtin::BI__sync_fetch_and_or_2:
  178. case Builtin::BI__sync_fetch_and_or_4:
  179. case Builtin::BI__sync_fetch_and_or_8:
  180. case Builtin::BI__sync_fetch_and_or_16:
  181. case Builtin::BI__sync_fetch_and_and:
  182. case Builtin::BI__sync_fetch_and_and_1:
  183. case Builtin::BI__sync_fetch_and_and_2:
  184. case Builtin::BI__sync_fetch_and_and_4:
  185. case Builtin::BI__sync_fetch_and_and_8:
  186. case Builtin::BI__sync_fetch_and_and_16:
  187. case Builtin::BI__sync_fetch_and_xor:
  188. case Builtin::BI__sync_fetch_and_xor_1:
  189. case Builtin::BI__sync_fetch_and_xor_2:
  190. case Builtin::BI__sync_fetch_and_xor_4:
  191. case Builtin::BI__sync_fetch_and_xor_8:
  192. case Builtin::BI__sync_fetch_and_xor_16:
  193. case Builtin::BI__sync_add_and_fetch:
  194. case Builtin::BI__sync_add_and_fetch_1:
  195. case Builtin::BI__sync_add_and_fetch_2:
  196. case Builtin::BI__sync_add_and_fetch_4:
  197. case Builtin::BI__sync_add_and_fetch_8:
  198. case Builtin::BI__sync_add_and_fetch_16:
  199. case Builtin::BI__sync_sub_and_fetch:
  200. case Builtin::BI__sync_sub_and_fetch_1:
  201. case Builtin::BI__sync_sub_and_fetch_2:
  202. case Builtin::BI__sync_sub_and_fetch_4:
  203. case Builtin::BI__sync_sub_and_fetch_8:
  204. case Builtin::BI__sync_sub_and_fetch_16:
  205. case Builtin::BI__sync_and_and_fetch:
  206. case Builtin::BI__sync_and_and_fetch_1:
  207. case Builtin::BI__sync_and_and_fetch_2:
  208. case Builtin::BI__sync_and_and_fetch_4:
  209. case Builtin::BI__sync_and_and_fetch_8:
  210. case Builtin::BI__sync_and_and_fetch_16:
  211. case Builtin::BI__sync_or_and_fetch:
  212. case Builtin::BI__sync_or_and_fetch_1:
  213. case Builtin::BI__sync_or_and_fetch_2:
  214. case Builtin::BI__sync_or_and_fetch_4:
  215. case Builtin::BI__sync_or_and_fetch_8:
  216. case Builtin::BI__sync_or_and_fetch_16:
  217. case Builtin::BI__sync_xor_and_fetch:
  218. case Builtin::BI__sync_xor_and_fetch_1:
  219. case Builtin::BI__sync_xor_and_fetch_2:
  220. case Builtin::BI__sync_xor_and_fetch_4:
  221. case Builtin::BI__sync_xor_and_fetch_8:
  222. case Builtin::BI__sync_xor_and_fetch_16:
  223. case Builtin::BI__sync_val_compare_and_swap:
  224. case Builtin::BI__sync_val_compare_and_swap_1:
  225. case Builtin::BI__sync_val_compare_and_swap_2:
  226. case Builtin::BI__sync_val_compare_and_swap_4:
  227. case Builtin::BI__sync_val_compare_and_swap_8:
  228. case Builtin::BI__sync_val_compare_and_swap_16:
  229. case Builtin::BI__sync_bool_compare_and_swap:
  230. case Builtin::BI__sync_bool_compare_and_swap_1:
  231. case Builtin::BI__sync_bool_compare_and_swap_2:
  232. case Builtin::BI__sync_bool_compare_and_swap_4:
  233. case Builtin::BI__sync_bool_compare_and_swap_8:
  234. case Builtin::BI__sync_bool_compare_and_swap_16:
  235. case Builtin::BI__sync_lock_test_and_set:
  236. case Builtin::BI__sync_lock_test_and_set_1:
  237. case Builtin::BI__sync_lock_test_and_set_2:
  238. case Builtin::BI__sync_lock_test_and_set_4:
  239. case Builtin::BI__sync_lock_test_and_set_8:
  240. case Builtin::BI__sync_lock_test_and_set_16:
  241. case Builtin::BI__sync_lock_release:
  242. case Builtin::BI__sync_lock_release_1:
  243. case Builtin::BI__sync_lock_release_2:
  244. case Builtin::BI__sync_lock_release_4:
  245. case Builtin::BI__sync_lock_release_8:
  246. case Builtin::BI__sync_lock_release_16:
  247. case Builtin::BI__sync_swap:
  248. case Builtin::BI__sync_swap_1:
  249. case Builtin::BI__sync_swap_2:
  250. case Builtin::BI__sync_swap_4:
  251. case Builtin::BI__sync_swap_8:
  252. case Builtin::BI__sync_swap_16:
  253. return SemaBuiltinAtomicOverloaded(TheCallResult);
  254. #define BUILTIN(ID, TYPE, ATTRS)
  255. #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
  256. case Builtin::BI##ID: \
  257. return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
  258. #include "clang/Basic/Builtins.def"
  259. case Builtin::BI__builtin_annotation:
  260. if (SemaBuiltinAnnotation(*this, TheCall))
  261. return ExprError();
  262. break;
  263. }
  264. // Since the target specific builtins for each arch overlap, only check those
  265. // of the arch we are compiling for.
  266. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  267. switch (Context.getTargetInfo().getTriple().getArch()) {
  268. case llvm::Triple::arm:
  269. case llvm::Triple::thumb:
  270. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  271. return ExprError();
  272. break;
  273. case llvm::Triple::mips:
  274. case llvm::Triple::mipsel:
  275. case llvm::Triple::mips64:
  276. case llvm::Triple::mips64el:
  277. if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
  278. return ExprError();
  279. break;
  280. default:
  281. break;
  282. }
  283. }
  284. return TheCallResult;
  285. }
  286. // Get the valid immediate range for the specified NEON type code.
  287. static unsigned RFT(unsigned t, bool shift = false) {
  288. NeonTypeFlags Type(t);
  289. int IsQuad = Type.isQuad();
  290. switch (Type.getEltType()) {
  291. case NeonTypeFlags::Int8:
  292. case NeonTypeFlags::Poly8:
  293. return shift ? 7 : (8 << IsQuad) - 1;
  294. case NeonTypeFlags::Int16:
  295. case NeonTypeFlags::Poly16:
  296. return shift ? 15 : (4 << IsQuad) - 1;
  297. case NeonTypeFlags::Int32:
  298. return shift ? 31 : (2 << IsQuad) - 1;
  299. case NeonTypeFlags::Int64:
  300. return shift ? 63 : (1 << IsQuad) - 1;
  301. case NeonTypeFlags::Float16:
  302. assert(!shift && "cannot shift float types!");
  303. return (4 << IsQuad) - 1;
  304. case NeonTypeFlags::Float32:
  305. assert(!shift && "cannot shift float types!");
  306. return (2 << IsQuad) - 1;
  307. }
  308. llvm_unreachable("Invalid NeonTypeFlag!");
  309. }
  310. /// getNeonEltType - Return the QualType corresponding to the elements of
  311. /// the vector type specified by the NeonTypeFlags. This is used to check
  312. /// the pointer arguments for Neon load/store intrinsics.
  313. static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
  314. switch (Flags.getEltType()) {
  315. case NeonTypeFlags::Int8:
  316. return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
  317. case NeonTypeFlags::Int16:
  318. return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
  319. case NeonTypeFlags::Int32:
  320. return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
  321. case NeonTypeFlags::Int64:
  322. return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
  323. case NeonTypeFlags::Poly8:
  324. return Context.SignedCharTy;
  325. case NeonTypeFlags::Poly16:
  326. return Context.ShortTy;
  327. case NeonTypeFlags::Float16:
  328. return Context.UnsignedShortTy;
  329. case NeonTypeFlags::Float32:
  330. return Context.FloatTy;
  331. }
  332. llvm_unreachable("Invalid NeonTypeFlag!");
  333. }
  334. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  335. llvm::APSInt Result;
  336. uint64_t mask = 0;
  337. unsigned TV = 0;
  338. int PtrArgNum = -1;
  339. bool HasConstPtr = false;
  340. switch (BuiltinID) {
  341. #define GET_NEON_OVERLOAD_CHECK
  342. #include "clang/Basic/arm_neon.inc"
  343. #undef GET_NEON_OVERLOAD_CHECK
  344. }
  345. // For NEON intrinsics which are overloaded on vector element type, validate
  346. // the immediate which specifies which variant to emit.
  347. unsigned ImmArg = TheCall->getNumArgs()-1;
  348. if (mask) {
  349. if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
  350. return true;
  351. TV = Result.getLimitedValue(64);
  352. if ((TV > 63) || (mask & (1ULL << TV)) == 0)
  353. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  354. << TheCall->getArg(ImmArg)->getSourceRange();
  355. }
  356. if (PtrArgNum >= 0) {
  357. // Check that pointer arguments have the specified type.
  358. Expr *Arg = TheCall->getArg(PtrArgNum);
  359. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
  360. Arg = ICE->getSubExpr();
  361. ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
  362. QualType RHSTy = RHS.get()->getType();
  363. QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
  364. if (HasConstPtr)
  365. EltTy = EltTy.withConst();
  366. QualType LHSTy = Context.getPointerType(EltTy);
  367. AssignConvertType ConvTy;
  368. ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
  369. if (RHS.isInvalid())
  370. return true;
  371. if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
  372. RHS.get(), AA_Assigning))
  373. return true;
  374. }
  375. // For NEON intrinsics which take an immediate value as part of the
  376. // instruction, range check them here.
  377. unsigned i = 0, l = 0, u = 0;
  378. switch (BuiltinID) {
  379. default: return false;
  380. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  381. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  382. case ARM::BI__builtin_arm_vcvtr_f:
  383. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  384. #define GET_NEON_IMMEDIATE_CHECK
  385. #include "clang/Basic/arm_neon.inc"
  386. #undef GET_NEON_IMMEDIATE_CHECK
  387. };
  388. // We can't check the value of a dependent argument.
  389. if (TheCall->getArg(i)->isTypeDependent() ||
  390. TheCall->getArg(i)->isValueDependent())
  391. return false;
  392. // Check that the immediate argument is actually a constant.
  393. if (SemaBuiltinConstantArg(TheCall, i, Result))
  394. return true;
  395. // Range check against the upper/lower values for this isntruction.
  396. unsigned Val = Result.getZExtValue();
  397. if (Val < l || Val > (u + l))
  398. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  399. << l << u+l << TheCall->getArg(i)->getSourceRange();
  400. // FIXME: VFP Intrinsics should error if VFP not present.
  401. return false;
  402. }
  403. bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  404. unsigned i = 0, l = 0, u = 0;
  405. switch (BuiltinID) {
  406. default: return false;
  407. case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
  408. case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
  409. case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
  410. case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
  411. case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
  412. case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
  413. case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
  414. };
  415. // We can't check the value of a dependent argument.
  416. if (TheCall->getArg(i)->isTypeDependent() ||
  417. TheCall->getArg(i)->isValueDependent())
  418. return false;
  419. // Check that the immediate argument is actually a constant.
  420. llvm::APSInt Result;
  421. if (SemaBuiltinConstantArg(TheCall, i, Result))
  422. return true;
  423. // Range check against the upper/lower values for this instruction.
  424. unsigned Val = Result.getZExtValue();
  425. if (Val < l || Val > u)
  426. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  427. << l << u << TheCall->getArg(i)->getSourceRange();
  428. return false;
  429. }
  430. /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
  431. /// parameter with the FormatAttr's correct format_idx and firstDataArg.
  432. /// Returns true when the format fits the function and the FormatStringInfo has
  433. /// been populated.
  434. bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
  435. FormatStringInfo *FSI) {
  436. FSI->HasVAListArg = Format->getFirstArg() == 0;
  437. FSI->FormatIdx = Format->getFormatIdx() - 1;
  438. FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
  439. // The way the format attribute works in GCC, the implicit this argument
  440. // of member functions is counted. However, it doesn't appear in our own
  441. // lists, so decrement format_idx in that case.
  442. if (IsCXXMember) {
  443. if(FSI->FormatIdx == 0)
  444. return false;
  445. --FSI->FormatIdx;
  446. if (FSI->FirstDataArg != 0)
  447. --FSI->FirstDataArg;
  448. }
  449. return true;
  450. }
  451. /// Handles the checks for format strings, non-POD arguments to vararg
  452. /// functions, and NULL arguments passed to non-NULL parameters.
  453. void Sema::checkCall(NamedDecl *FDecl, Expr **Args,
  454. unsigned NumArgs,
  455. unsigned NumProtoArgs,
  456. bool IsMemberFunction,
  457. SourceLocation Loc,
  458. SourceRange Range,
  459. VariadicCallType CallType) {
  460. // FIXME: This mechanism should be abstracted to be less fragile and
  461. // more efficient. For example, just map function ids to custom
  462. // handlers.
  463. // Printf and scanf checking.
  464. bool HandledFormatString = false;
  465. for (specific_attr_iterator<FormatAttr>
  466. I = FDecl->specific_attr_begin<FormatAttr>(),
  467. E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
  468. if (CheckFormatArguments(*I, Args, NumArgs, IsMemberFunction, CallType,
  469. Loc, Range))
  470. HandledFormatString = true;
  471. // Refuse POD arguments that weren't caught by the format string
  472. // checks above.
  473. if (!HandledFormatString && CallType != VariadicDoesNotApply)
  474. for (unsigned ArgIdx = NumProtoArgs; ArgIdx < NumArgs; ++ArgIdx)
  475. variadicArgumentPODCheck(Args[ArgIdx], CallType);
  476. for (specific_attr_iterator<NonNullAttr>
  477. I = FDecl->specific_attr_begin<NonNullAttr>(),
  478. E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
  479. CheckNonNullArguments(*I, Args, Loc);
  480. // Type safety checking.
  481. for (specific_attr_iterator<ArgumentWithTypeTagAttr>
  482. i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
  483. e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>(); i != e; ++i) {
  484. CheckArgumentWithTypeTag(*i, Args);
  485. }
  486. }
  487. /// CheckConstructorCall - Check a constructor call for correctness and safety
  488. /// properties not enforced by the C type system.
  489. void Sema::CheckConstructorCall(FunctionDecl *FDecl, Expr **Args,
  490. unsigned NumArgs,
  491. const FunctionProtoType *Proto,
  492. SourceLocation Loc) {
  493. VariadicCallType CallType =
  494. Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
  495. checkCall(FDecl, Args, NumArgs, Proto->getNumArgs(),
  496. /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
  497. }
  498. /// CheckFunctionCall - Check a direct function call for various correctness
  499. /// and safety properties not strictly enforced by the C type system.
  500. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
  501. const FunctionProtoType *Proto) {
  502. bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall);
  503. VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
  504. TheCall->getCallee());
  505. unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
  506. checkCall(FDecl, TheCall->getArgs(), TheCall->getNumArgs(), NumProtoArgs,
  507. IsMemberFunction, TheCall->getRParenLoc(),
  508. TheCall->getCallee()->getSourceRange(), CallType);
  509. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  510. // None of the checks below are needed for functions that don't have
  511. // simple names (e.g., C++ conversion functions).
  512. if (!FnInfo)
  513. return false;
  514. unsigned CMId = FDecl->getMemoryFunctionKind();
  515. if (CMId == 0)
  516. return false;
  517. // Handle memory setting and copying functions.
  518. if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
  519. CheckStrlcpycatArguments(TheCall, FnInfo);
  520. else if (CMId == Builtin::BIstrncat)
  521. CheckStrncatArguments(TheCall, FnInfo);
  522. else
  523. CheckMemaccessArguments(TheCall, CMId, FnInfo);
  524. return false;
  525. }
  526. bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
  527. Expr **Args, unsigned NumArgs) {
  528. VariadicCallType CallType =
  529. Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
  530. checkCall(Method, Args, NumArgs, Method->param_size(),
  531. /*IsMemberFunction=*/false,
  532. lbrac, Method->getSourceRange(), CallType);
  533. return false;
  534. }
  535. bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall,
  536. const FunctionProtoType *Proto) {
  537. const VarDecl *V = dyn_cast<VarDecl>(NDecl);
  538. if (!V)
  539. return false;
  540. QualType Ty = V->getType();
  541. if (!Ty->isBlockPointerType())
  542. return false;
  543. VariadicCallType CallType =
  544. Proto && Proto->isVariadic() ? VariadicBlock : VariadicDoesNotApply ;
  545. unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
  546. checkCall(NDecl, TheCall->getArgs(), TheCall->getNumArgs(),
  547. NumProtoArgs, /*IsMemberFunction=*/false,
  548. TheCall->getRParenLoc(),
  549. TheCall->getCallee()->getSourceRange(), CallType);
  550. return false;
  551. }
  552. ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
  553. AtomicExpr::AtomicOp Op) {
  554. CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
  555. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  556. // All these operations take one of the following forms:
  557. enum {
  558. // C __c11_atomic_init(A *, C)
  559. Init,
  560. // C __c11_atomic_load(A *, int)
  561. Load,
  562. // void __atomic_load(A *, CP, int)
  563. Copy,
  564. // C __c11_atomic_add(A *, M, int)
  565. Arithmetic,
  566. // C __atomic_exchange_n(A *, CP, int)
  567. Xchg,
  568. // void __atomic_exchange(A *, C *, CP, int)
  569. GNUXchg,
  570. // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
  571. C11CmpXchg,
  572. // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
  573. GNUCmpXchg
  574. } Form = Init;
  575. const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
  576. const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
  577. // where:
  578. // C is an appropriate type,
  579. // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
  580. // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
  581. // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
  582. // the int parameters are for orderings.
  583. assert(AtomicExpr::AO__c11_atomic_init == 0 &&
  584. AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
  585. && "need to update code for modified C11 atomics");
  586. bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
  587. Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
  588. bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
  589. Op == AtomicExpr::AO__atomic_store_n ||
  590. Op == AtomicExpr::AO__atomic_exchange_n ||
  591. Op == AtomicExpr::AO__atomic_compare_exchange_n;
  592. bool IsAddSub = false;
  593. switch (Op) {
  594. case AtomicExpr::AO__c11_atomic_init:
  595. Form = Init;
  596. break;
  597. case AtomicExpr::AO__c11_atomic_load:
  598. case AtomicExpr::AO__atomic_load_n:
  599. Form = Load;
  600. break;
  601. case AtomicExpr::AO__c11_atomic_store:
  602. case AtomicExpr::AO__atomic_load:
  603. case AtomicExpr::AO__atomic_store:
  604. case AtomicExpr::AO__atomic_store_n:
  605. Form = Copy;
  606. break;
  607. case AtomicExpr::AO__c11_atomic_fetch_add:
  608. case AtomicExpr::AO__c11_atomic_fetch_sub:
  609. case AtomicExpr::AO__atomic_fetch_add:
  610. case AtomicExpr::AO__atomic_fetch_sub:
  611. case AtomicExpr::AO__atomic_add_fetch:
  612. case AtomicExpr::AO__atomic_sub_fetch:
  613. IsAddSub = true;
  614. // Fall through.
  615. case AtomicExpr::AO__c11_atomic_fetch_and:
  616. case AtomicExpr::AO__c11_atomic_fetch_or:
  617. case AtomicExpr::AO__c11_atomic_fetch_xor:
  618. case AtomicExpr::AO__atomic_fetch_and:
  619. case AtomicExpr::AO__atomic_fetch_or:
  620. case AtomicExpr::AO__atomic_fetch_xor:
  621. case AtomicExpr::AO__atomic_fetch_nand:
  622. case AtomicExpr::AO__atomic_and_fetch:
  623. case AtomicExpr::AO__atomic_or_fetch:
  624. case AtomicExpr::AO__atomic_xor_fetch:
  625. case AtomicExpr::AO__atomic_nand_fetch:
  626. Form = Arithmetic;
  627. break;
  628. case AtomicExpr::AO__c11_atomic_exchange:
  629. case AtomicExpr::AO__atomic_exchange_n:
  630. Form = Xchg;
  631. break;
  632. case AtomicExpr::AO__atomic_exchange:
  633. Form = GNUXchg;
  634. break;
  635. case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
  636. case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
  637. Form = C11CmpXchg;
  638. break;
  639. case AtomicExpr::AO__atomic_compare_exchange:
  640. case AtomicExpr::AO__atomic_compare_exchange_n:
  641. Form = GNUCmpXchg;
  642. break;
  643. }
  644. // Check we have the right number of arguments.
  645. if (TheCall->getNumArgs() < NumArgs[Form]) {
  646. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  647. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  648. << TheCall->getCallee()->getSourceRange();
  649. return ExprError();
  650. } else if (TheCall->getNumArgs() > NumArgs[Form]) {
  651. Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
  652. diag::err_typecheck_call_too_many_args)
  653. << 0 << NumArgs[Form] << TheCall->getNumArgs()
  654. << TheCall->getCallee()->getSourceRange();
  655. return ExprError();
  656. }
  657. // Inspect the first argument of the atomic operation.
  658. Expr *Ptr = TheCall->getArg(0);
  659. Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
  660. const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
  661. if (!pointerType) {
  662. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  663. << Ptr->getType() << Ptr->getSourceRange();
  664. return ExprError();
  665. }
  666. // For a __c11 builtin, this should be a pointer to an _Atomic type.
  667. QualType AtomTy = pointerType->getPointeeType(); // 'A'
  668. QualType ValType = AtomTy; // 'C'
  669. if (IsC11) {
  670. if (!AtomTy->isAtomicType()) {
  671. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
  672. << Ptr->getType() << Ptr->getSourceRange();
  673. return ExprError();
  674. }
  675. ValType = AtomTy->getAs<AtomicType>()->getValueType();
  676. }
  677. // For an arithmetic operation, the implied arithmetic must be well-formed.
  678. if (Form == Arithmetic) {
  679. // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
  680. if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
  681. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  682. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  683. return ExprError();
  684. }
  685. if (!IsAddSub && !ValType->isIntegerType()) {
  686. Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
  687. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  688. return ExprError();
  689. }
  690. } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
  691. // For __atomic_*_n operations, the value type must be a scalar integral or
  692. // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
  693. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
  694. << IsC11 << Ptr->getType() << Ptr->getSourceRange();
  695. return ExprError();
  696. }
  697. if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
  698. // For GNU atomics, require a trivially-copyable type. This is not part of
  699. // the GNU atomics specification, but we enforce it for sanity.
  700. Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
  701. << Ptr->getType() << Ptr->getSourceRange();
  702. return ExprError();
  703. }
  704. // FIXME: For any builtin other than a load, the ValType must not be
  705. // const-qualified.
  706. switch (ValType.getObjCLifetime()) {
  707. case Qualifiers::OCL_None:
  708. case Qualifiers::OCL_ExplicitNone:
  709. // okay
  710. break;
  711. case Qualifiers::OCL_Weak:
  712. case Qualifiers::OCL_Strong:
  713. case Qualifiers::OCL_Autoreleasing:
  714. // FIXME: Can this happen? By this point, ValType should be known
  715. // to be trivially copyable.
  716. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  717. << ValType << Ptr->getSourceRange();
  718. return ExprError();
  719. }
  720. QualType ResultType = ValType;
  721. if (Form == Copy || Form == GNUXchg || Form == Init)
  722. ResultType = Context.VoidTy;
  723. else if (Form == C11CmpXchg || Form == GNUCmpXchg)
  724. ResultType = Context.BoolTy;
  725. // The type of a parameter passed 'by value'. In the GNU atomics, such
  726. // arguments are actually passed as pointers.
  727. QualType ByValType = ValType; // 'CP'
  728. if (!IsC11 && !IsN)
  729. ByValType = Ptr->getType();
  730. // The first argument --- the pointer --- has a fixed type; we
  731. // deduce the types of the rest of the arguments accordingly. Walk
  732. // the remaining arguments, converting them to the deduced value type.
  733. for (unsigned i = 1; i != NumArgs[Form]; ++i) {
  734. QualType Ty;
  735. if (i < NumVals[Form] + 1) {
  736. switch (i) {
  737. case 1:
  738. // The second argument is the non-atomic operand. For arithmetic, this
  739. // is always passed by value, and for a compare_exchange it is always
  740. // passed by address. For the rest, GNU uses by-address and C11 uses
  741. // by-value.
  742. assert(Form != Load);
  743. if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
  744. Ty = ValType;
  745. else if (Form == Copy || Form == Xchg)
  746. Ty = ByValType;
  747. else if (Form == Arithmetic)
  748. Ty = Context.getPointerDiffType();
  749. else
  750. Ty = Context.getPointerType(ValType.getUnqualifiedType());
  751. break;
  752. case 2:
  753. // The third argument to compare_exchange / GNU exchange is a
  754. // (pointer to a) desired value.
  755. Ty = ByValType;
  756. break;
  757. case 3:
  758. // The fourth argument to GNU compare_exchange is a 'weak' flag.
  759. Ty = Context.BoolTy;
  760. break;
  761. }
  762. } else {
  763. // The order(s) are always converted to int.
  764. Ty = Context.IntTy;
  765. }
  766. InitializedEntity Entity =
  767. InitializedEntity::InitializeParameter(Context, Ty, false);
  768. ExprResult Arg = TheCall->getArg(i);
  769. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  770. if (Arg.isInvalid())
  771. return true;
  772. TheCall->setArg(i, Arg.get());
  773. }
  774. // Permute the arguments into a 'consistent' order.
  775. SmallVector<Expr*, 5> SubExprs;
  776. SubExprs.push_back(Ptr);
  777. switch (Form) {
  778. case Init:
  779. // Note, AtomicExpr::getVal1() has a special case for this atomic.
  780. SubExprs.push_back(TheCall->getArg(1)); // Val1
  781. break;
  782. case Load:
  783. SubExprs.push_back(TheCall->getArg(1)); // Order
  784. break;
  785. case Copy:
  786. case Arithmetic:
  787. case Xchg:
  788. SubExprs.push_back(TheCall->getArg(2)); // Order
  789. SubExprs.push_back(TheCall->getArg(1)); // Val1
  790. break;
  791. case GNUXchg:
  792. // Note, AtomicExpr::getVal2() has a special case for this atomic.
  793. SubExprs.push_back(TheCall->getArg(3)); // Order
  794. SubExprs.push_back(TheCall->getArg(1)); // Val1
  795. SubExprs.push_back(TheCall->getArg(2)); // Val2
  796. break;
  797. case C11CmpXchg:
  798. SubExprs.push_back(TheCall->getArg(3)); // Order
  799. SubExprs.push_back(TheCall->getArg(1)); // Val1
  800. SubExprs.push_back(TheCall->getArg(4)); // OrderFail
  801. SubExprs.push_back(TheCall->getArg(2)); // Val2
  802. break;
  803. case GNUCmpXchg:
  804. SubExprs.push_back(TheCall->getArg(4)); // Order
  805. SubExprs.push_back(TheCall->getArg(1)); // Val1
  806. SubExprs.push_back(TheCall->getArg(5)); // OrderFail
  807. SubExprs.push_back(TheCall->getArg(2)); // Val2
  808. SubExprs.push_back(TheCall->getArg(3)); // Weak
  809. break;
  810. }
  811. return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
  812. SubExprs, ResultType, Op,
  813. TheCall->getRParenLoc()));
  814. }
  815. /// checkBuiltinArgument - Given a call to a builtin function, perform
  816. /// normal type-checking on the given argument, updating the call in
  817. /// place. This is useful when a builtin function requires custom
  818. /// type-checking for some of its arguments but not necessarily all of
  819. /// them.
  820. ///
  821. /// Returns true on error.
  822. static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
  823. FunctionDecl *Fn = E->getDirectCallee();
  824. assert(Fn && "builtin call without direct callee!");
  825. ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
  826. InitializedEntity Entity =
  827. InitializedEntity::InitializeParameter(S.Context, Param);
  828. ExprResult Arg = E->getArg(0);
  829. Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
  830. if (Arg.isInvalid())
  831. return true;
  832. E->setArg(ArgIndex, Arg.take());
  833. return false;
  834. }
  835. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  836. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  837. /// type of its first argument. The main ActOnCallExpr routines have already
  838. /// promoted the types of arguments because all of these calls are prototyped as
  839. /// void(...).
  840. ///
  841. /// This function goes through and does final semantic checking for these
  842. /// builtins,
  843. ExprResult
  844. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  845. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  846. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  847. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  848. // Ensure that we have at least one argument to do type inference from.
  849. if (TheCall->getNumArgs() < 1) {
  850. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  851. << 0 << 1 << TheCall->getNumArgs()
  852. << TheCall->getCallee()->getSourceRange();
  853. return ExprError();
  854. }
  855. // Inspect the first argument of the atomic builtin. This should always be
  856. // a pointer type, whose element is an integral scalar or pointer type.
  857. // Because it is a pointer type, we don't have to worry about any implicit
  858. // casts here.
  859. // FIXME: We don't allow floating point scalars as input.
  860. Expr *FirstArg = TheCall->getArg(0);
  861. ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
  862. if (FirstArgResult.isInvalid())
  863. return ExprError();
  864. FirstArg = FirstArgResult.take();
  865. TheCall->setArg(0, FirstArg);
  866. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  867. if (!pointerType) {
  868. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  869. << FirstArg->getType() << FirstArg->getSourceRange();
  870. return ExprError();
  871. }
  872. QualType ValType = pointerType->getPointeeType();
  873. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  874. !ValType->isBlockPointerType()) {
  875. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  876. << FirstArg->getType() << FirstArg->getSourceRange();
  877. return ExprError();
  878. }
  879. switch (ValType.getObjCLifetime()) {
  880. case Qualifiers::OCL_None:
  881. case Qualifiers::OCL_ExplicitNone:
  882. // okay
  883. break;
  884. case Qualifiers::OCL_Weak:
  885. case Qualifiers::OCL_Strong:
  886. case Qualifiers::OCL_Autoreleasing:
  887. Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
  888. << ValType << FirstArg->getSourceRange();
  889. return ExprError();
  890. }
  891. // Strip any qualifiers off ValType.
  892. ValType = ValType.getUnqualifiedType();
  893. // The majority of builtins return a value, but a few have special return
  894. // types, so allow them to override appropriately below.
  895. QualType ResultType = ValType;
  896. // We need to figure out which concrete builtin this maps onto. For example,
  897. // __sync_fetch_and_add with a 2 byte object turns into
  898. // __sync_fetch_and_add_2.
  899. #define BUILTIN_ROW(x) \
  900. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  901. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  902. static const unsigned BuiltinIndices[][5] = {
  903. BUILTIN_ROW(__sync_fetch_and_add),
  904. BUILTIN_ROW(__sync_fetch_and_sub),
  905. BUILTIN_ROW(__sync_fetch_and_or),
  906. BUILTIN_ROW(__sync_fetch_and_and),
  907. BUILTIN_ROW(__sync_fetch_and_xor),
  908. BUILTIN_ROW(__sync_add_and_fetch),
  909. BUILTIN_ROW(__sync_sub_and_fetch),
  910. BUILTIN_ROW(__sync_and_and_fetch),
  911. BUILTIN_ROW(__sync_or_and_fetch),
  912. BUILTIN_ROW(__sync_xor_and_fetch),
  913. BUILTIN_ROW(__sync_val_compare_and_swap),
  914. BUILTIN_ROW(__sync_bool_compare_and_swap),
  915. BUILTIN_ROW(__sync_lock_test_and_set),
  916. BUILTIN_ROW(__sync_lock_release),
  917. BUILTIN_ROW(__sync_swap)
  918. };
  919. #undef BUILTIN_ROW
  920. // Determine the index of the size.
  921. unsigned SizeIndex;
  922. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  923. case 1: SizeIndex = 0; break;
  924. case 2: SizeIndex = 1; break;
  925. case 4: SizeIndex = 2; break;
  926. case 8: SizeIndex = 3; break;
  927. case 16: SizeIndex = 4; break;
  928. default:
  929. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  930. << FirstArg->getType() << FirstArg->getSourceRange();
  931. return ExprError();
  932. }
  933. // Each of these builtins has one pointer argument, followed by some number of
  934. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  935. // that we ignore. Find out which row of BuiltinIndices to read from as well
  936. // as the number of fixed args.
  937. unsigned BuiltinID = FDecl->getBuiltinID();
  938. unsigned BuiltinIndex, NumFixed = 1;
  939. switch (BuiltinID) {
  940. default: llvm_unreachable("Unknown overloaded atomic builtin!");
  941. case Builtin::BI__sync_fetch_and_add:
  942. case Builtin::BI__sync_fetch_and_add_1:
  943. case Builtin::BI__sync_fetch_and_add_2:
  944. case Builtin::BI__sync_fetch_and_add_4:
  945. case Builtin::BI__sync_fetch_and_add_8:
  946. case Builtin::BI__sync_fetch_and_add_16:
  947. BuiltinIndex = 0;
  948. break;
  949. case Builtin::BI__sync_fetch_and_sub:
  950. case Builtin::BI__sync_fetch_and_sub_1:
  951. case Builtin::BI__sync_fetch_and_sub_2:
  952. case Builtin::BI__sync_fetch_and_sub_4:
  953. case Builtin::BI__sync_fetch_and_sub_8:
  954. case Builtin::BI__sync_fetch_and_sub_16:
  955. BuiltinIndex = 1;
  956. break;
  957. case Builtin::BI__sync_fetch_and_or:
  958. case Builtin::BI__sync_fetch_and_or_1:
  959. case Builtin::BI__sync_fetch_and_or_2:
  960. case Builtin::BI__sync_fetch_and_or_4:
  961. case Builtin::BI__sync_fetch_and_or_8:
  962. case Builtin::BI__sync_fetch_and_or_16:
  963. BuiltinIndex = 2;
  964. break;
  965. case Builtin::BI__sync_fetch_and_and:
  966. case Builtin::BI__sync_fetch_and_and_1:
  967. case Builtin::BI__sync_fetch_and_and_2:
  968. case Builtin::BI__sync_fetch_and_and_4:
  969. case Builtin::BI__sync_fetch_and_and_8:
  970. case Builtin::BI__sync_fetch_and_and_16:
  971. BuiltinIndex = 3;
  972. break;
  973. case Builtin::BI__sync_fetch_and_xor:
  974. case Builtin::BI__sync_fetch_and_xor_1:
  975. case Builtin::BI__sync_fetch_and_xor_2:
  976. case Builtin::BI__sync_fetch_and_xor_4:
  977. case Builtin::BI__sync_fetch_and_xor_8:
  978. case Builtin::BI__sync_fetch_and_xor_16:
  979. BuiltinIndex = 4;
  980. break;
  981. case Builtin::BI__sync_add_and_fetch:
  982. case Builtin::BI__sync_add_and_fetch_1:
  983. case Builtin::BI__sync_add_and_fetch_2:
  984. case Builtin::BI__sync_add_and_fetch_4:
  985. case Builtin::BI__sync_add_and_fetch_8:
  986. case Builtin::BI__sync_add_and_fetch_16:
  987. BuiltinIndex = 5;
  988. break;
  989. case Builtin::BI__sync_sub_and_fetch:
  990. case Builtin::BI__sync_sub_and_fetch_1:
  991. case Builtin::BI__sync_sub_and_fetch_2:
  992. case Builtin::BI__sync_sub_and_fetch_4:
  993. case Builtin::BI__sync_sub_and_fetch_8:
  994. case Builtin::BI__sync_sub_and_fetch_16:
  995. BuiltinIndex = 6;
  996. break;
  997. case Builtin::BI__sync_and_and_fetch:
  998. case Builtin::BI__sync_and_and_fetch_1:
  999. case Builtin::BI__sync_and_and_fetch_2:
  1000. case Builtin::BI__sync_and_and_fetch_4:
  1001. case Builtin::BI__sync_and_and_fetch_8:
  1002. case Builtin::BI__sync_and_and_fetch_16:
  1003. BuiltinIndex = 7;
  1004. break;
  1005. case Builtin::BI__sync_or_and_fetch:
  1006. case Builtin::BI__sync_or_and_fetch_1:
  1007. case Builtin::BI__sync_or_and_fetch_2:
  1008. case Builtin::BI__sync_or_and_fetch_4:
  1009. case Builtin::BI__sync_or_and_fetch_8:
  1010. case Builtin::BI__sync_or_and_fetch_16:
  1011. BuiltinIndex = 8;
  1012. break;
  1013. case Builtin::BI__sync_xor_and_fetch:
  1014. case Builtin::BI__sync_xor_and_fetch_1:
  1015. case Builtin::BI__sync_xor_and_fetch_2:
  1016. case Builtin::BI__sync_xor_and_fetch_4:
  1017. case Builtin::BI__sync_xor_and_fetch_8:
  1018. case Builtin::BI__sync_xor_and_fetch_16:
  1019. BuiltinIndex = 9;
  1020. break;
  1021. case Builtin::BI__sync_val_compare_and_swap:
  1022. case Builtin::BI__sync_val_compare_and_swap_1:
  1023. case Builtin::BI__sync_val_compare_and_swap_2:
  1024. case Builtin::BI__sync_val_compare_and_swap_4:
  1025. case Builtin::BI__sync_val_compare_and_swap_8:
  1026. case Builtin::BI__sync_val_compare_and_swap_16:
  1027. BuiltinIndex = 10;
  1028. NumFixed = 2;
  1029. break;
  1030. case Builtin::BI__sync_bool_compare_and_swap:
  1031. case Builtin::BI__sync_bool_compare_and_swap_1:
  1032. case Builtin::BI__sync_bool_compare_and_swap_2:
  1033. case Builtin::BI__sync_bool_compare_and_swap_4:
  1034. case Builtin::BI__sync_bool_compare_and_swap_8:
  1035. case Builtin::BI__sync_bool_compare_and_swap_16:
  1036. BuiltinIndex = 11;
  1037. NumFixed = 2;
  1038. ResultType = Context.BoolTy;
  1039. break;
  1040. case Builtin::BI__sync_lock_test_and_set:
  1041. case Builtin::BI__sync_lock_test_and_set_1:
  1042. case Builtin::BI__sync_lock_test_and_set_2:
  1043. case Builtin::BI__sync_lock_test_and_set_4:
  1044. case Builtin::BI__sync_lock_test_and_set_8:
  1045. case Builtin::BI__sync_lock_test_and_set_16:
  1046. BuiltinIndex = 12;
  1047. break;
  1048. case Builtin::BI__sync_lock_release:
  1049. case Builtin::BI__sync_lock_release_1:
  1050. case Builtin::BI__sync_lock_release_2:
  1051. case Builtin::BI__sync_lock_release_4:
  1052. case Builtin::BI__sync_lock_release_8:
  1053. case Builtin::BI__sync_lock_release_16:
  1054. BuiltinIndex = 13;
  1055. NumFixed = 0;
  1056. ResultType = Context.VoidTy;
  1057. break;
  1058. case Builtin::BI__sync_swap:
  1059. case Builtin::BI__sync_swap_1:
  1060. case Builtin::BI__sync_swap_2:
  1061. case Builtin::BI__sync_swap_4:
  1062. case Builtin::BI__sync_swap_8:
  1063. case Builtin::BI__sync_swap_16:
  1064. BuiltinIndex = 14;
  1065. break;
  1066. }
  1067. // Now that we know how many fixed arguments we expect, first check that we
  1068. // have at least that many.
  1069. if (TheCall->getNumArgs() < 1+NumFixed) {
  1070. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  1071. << 0 << 1+NumFixed << TheCall->getNumArgs()
  1072. << TheCall->getCallee()->getSourceRange();
  1073. return ExprError();
  1074. }
  1075. // Get the decl for the concrete builtin from this, we can tell what the
  1076. // concrete integer type we should convert to is.
  1077. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  1078. const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
  1079. IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
  1080. FunctionDecl *NewBuiltinDecl =
  1081. cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
  1082. TUScope, false, DRE->getLocStart()));
  1083. // The first argument --- the pointer --- has a fixed type; we
  1084. // deduce the types of the rest of the arguments accordingly. Walk
  1085. // the remaining arguments, converting them to the deduced value type.
  1086. for (unsigned i = 0; i != NumFixed; ++i) {
  1087. ExprResult Arg = TheCall->getArg(i+1);
  1088. // GCC does an implicit conversion to the pointer or integer ValType. This
  1089. // can fail in some cases (1i -> int**), check for this error case now.
  1090. // Initialize the argument.
  1091. InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
  1092. ValType, /*consume*/ false);
  1093. Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
  1094. if (Arg.isInvalid())
  1095. return ExprError();
  1096. // Okay, we have something that *can* be converted to the right type. Check
  1097. // to see if there is a potentially weird extension going on here. This can
  1098. // happen when you do an atomic operation on something like an char* and
  1099. // pass in 42. The 42 gets converted to char. This is even more strange
  1100. // for things like 45.123 -> char, etc.
  1101. // FIXME: Do this check.
  1102. TheCall->setArg(i+1, Arg.take());
  1103. }
  1104. ASTContext& Context = this->getASTContext();
  1105. // Create a new DeclRefExpr to refer to the new decl.
  1106. DeclRefExpr* NewDRE = DeclRefExpr::Create(
  1107. Context,
  1108. DRE->getQualifierLoc(),
  1109. SourceLocation(),
  1110. NewBuiltinDecl,
  1111. /*enclosing*/ false,
  1112. DRE->getLocation(),
  1113. Context.BuiltinFnTy,
  1114. DRE->getValueKind());
  1115. // Set the callee in the CallExpr.
  1116. // FIXME: This loses syntactic information.
  1117. QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
  1118. ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
  1119. CK_BuiltinFnToFnPtr);
  1120. TheCall->setCallee(PromotedCall.take());
  1121. // Change the result type of the call to match the original value type. This
  1122. // is arbitrary, but the codegen for these builtins ins design to handle it
  1123. // gracefully.
  1124. TheCall->setType(ResultType);
  1125. return TheCallResult;
  1126. }
  1127. /// CheckObjCString - Checks that the argument to the builtin
  1128. /// CFString constructor is correct
  1129. /// Note: It might also make sense to do the UTF-16 conversion here (would
  1130. /// simplify the backend).
  1131. bool Sema::CheckObjCString(Expr *Arg) {
  1132. Arg = Arg->IgnoreParenCasts();
  1133. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  1134. if (!Literal || !Literal->isAscii()) {
  1135. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  1136. << Arg->getSourceRange();
  1137. return true;
  1138. }
  1139. if (Literal->containsNonAsciiOrNull()) {
  1140. StringRef String = Literal->getString();
  1141. unsigned NumBytes = String.size();
  1142. SmallVector<UTF16, 128> ToBuf(NumBytes);
  1143. const UTF8 *FromPtr = (const UTF8 *)String.data();
  1144. UTF16 *ToPtr = &ToBuf[0];
  1145. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  1146. &ToPtr, ToPtr + NumBytes,
  1147. strictConversion);
  1148. // Check for conversion failure.
  1149. if (Result != conversionOK)
  1150. Diag(Arg->getLocStart(),
  1151. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  1152. }
  1153. return false;
  1154. }
  1155. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  1156. /// Emit an error and return true on failure, return false on success.
  1157. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  1158. Expr *Fn = TheCall->getCallee();
  1159. if (TheCall->getNumArgs() > 2) {
  1160. Diag(TheCall->getArg(2)->getLocStart(),
  1161. diag::err_typecheck_call_too_many_args)
  1162. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1163. << Fn->getSourceRange()
  1164. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1165. (*(TheCall->arg_end()-1))->getLocEnd());
  1166. return true;
  1167. }
  1168. if (TheCall->getNumArgs() < 2) {
  1169. return Diag(TheCall->getLocEnd(),
  1170. diag::err_typecheck_call_too_few_args_at_least)
  1171. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  1172. }
  1173. // Type-check the first argument normally.
  1174. if (checkBuiltinArgument(*this, TheCall, 0))
  1175. return true;
  1176. // Determine whether the current function is variadic or not.
  1177. BlockScopeInfo *CurBlock = getCurBlock();
  1178. bool isVariadic;
  1179. if (CurBlock)
  1180. isVariadic = CurBlock->TheDecl->isVariadic();
  1181. else if (FunctionDecl *FD = getCurFunctionDecl())
  1182. isVariadic = FD->isVariadic();
  1183. else
  1184. isVariadic = getCurMethodDecl()->isVariadic();
  1185. if (!isVariadic) {
  1186. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  1187. return true;
  1188. }
  1189. // Verify that the second argument to the builtin is the last argument of the
  1190. // current function or method.
  1191. bool SecondArgIsLastNamedArgument = false;
  1192. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  1193. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  1194. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  1195. // FIXME: This isn't correct for methods (results in bogus warning).
  1196. // Get the last formal in the current function.
  1197. const ParmVarDecl *LastArg;
  1198. if (CurBlock)
  1199. LastArg = *(CurBlock->TheDecl->param_end()-1);
  1200. else if (FunctionDecl *FD = getCurFunctionDecl())
  1201. LastArg = *(FD->param_end()-1);
  1202. else
  1203. LastArg = *(getCurMethodDecl()->param_end()-1);
  1204. SecondArgIsLastNamedArgument = PV == LastArg;
  1205. }
  1206. }
  1207. if (!SecondArgIsLastNamedArgument)
  1208. Diag(TheCall->getArg(1)->getLocStart(),
  1209. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  1210. return false;
  1211. }
  1212. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  1213. /// friends. This is declared to take (...), so we have to check everything.
  1214. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  1215. if (TheCall->getNumArgs() < 2)
  1216. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1217. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  1218. if (TheCall->getNumArgs() > 2)
  1219. return Diag(TheCall->getArg(2)->getLocStart(),
  1220. diag::err_typecheck_call_too_many_args)
  1221. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1222. << SourceRange(TheCall->getArg(2)->getLocStart(),
  1223. (*(TheCall->arg_end()-1))->getLocEnd());
  1224. ExprResult OrigArg0 = TheCall->getArg(0);
  1225. ExprResult OrigArg1 = TheCall->getArg(1);
  1226. // Do standard promotions between the two arguments, returning their common
  1227. // type.
  1228. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  1229. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  1230. return true;
  1231. // Make sure any conversions are pushed back into the call; this is
  1232. // type safe since unordered compare builtins are declared as "_Bool
  1233. // foo(...)".
  1234. TheCall->setArg(0, OrigArg0.get());
  1235. TheCall->setArg(1, OrigArg1.get());
  1236. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  1237. return false;
  1238. // If the common type isn't a real floating type, then the arguments were
  1239. // invalid for this operation.
  1240. if (Res.isNull() || !Res->isRealFloatingType())
  1241. return Diag(OrigArg0.get()->getLocStart(),
  1242. diag::err_typecheck_call_invalid_ordered_compare)
  1243. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  1244. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  1245. return false;
  1246. }
  1247. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  1248. /// __builtin_isnan and friends. This is declared to take (...), so we have
  1249. /// to check everything. We expect the last argument to be a floating point
  1250. /// value.
  1251. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  1252. if (TheCall->getNumArgs() < NumArgs)
  1253. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  1254. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  1255. if (TheCall->getNumArgs() > NumArgs)
  1256. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  1257. diag::err_typecheck_call_too_many_args)
  1258. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  1259. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  1260. (*(TheCall->arg_end()-1))->getLocEnd());
  1261. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  1262. if (OrigArg->isTypeDependent())
  1263. return false;
  1264. // This operation requires a non-_Complex floating-point number.
  1265. if (!OrigArg->getType()->isRealFloatingType())
  1266. return Diag(OrigArg->getLocStart(),
  1267. diag::err_typecheck_call_invalid_unary_fp)
  1268. << OrigArg->getType() << OrigArg->getSourceRange();
  1269. // If this is an implicit conversion from float -> double, remove it.
  1270. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  1271. Expr *CastArg = Cast->getSubExpr();
  1272. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  1273. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  1274. "promotion from float to double is the only expected cast here");
  1275. Cast->setSubExpr(0);
  1276. TheCall->setArg(NumArgs-1, CastArg);
  1277. }
  1278. }
  1279. return false;
  1280. }
  1281. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  1282. // This is declared to take (...), so we have to check everything.
  1283. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  1284. if (TheCall->getNumArgs() < 2)
  1285. return ExprError(Diag(TheCall->getLocEnd(),
  1286. diag::err_typecheck_call_too_few_args_at_least)
  1287. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  1288. << TheCall->getSourceRange());
  1289. // Determine which of the following types of shufflevector we're checking:
  1290. // 1) unary, vector mask: (lhs, mask)
  1291. // 2) binary, vector mask: (lhs, rhs, mask)
  1292. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  1293. QualType resType = TheCall->getArg(0)->getType();
  1294. unsigned numElements = 0;
  1295. if (!TheCall->getArg(0)->isTypeDependent() &&
  1296. !TheCall->getArg(1)->isTypeDependent()) {
  1297. QualType LHSType = TheCall->getArg(0)->getType();
  1298. QualType RHSType = TheCall->getArg(1)->getType();
  1299. if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
  1300. Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
  1301. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1302. TheCall->getArg(1)->getLocEnd());
  1303. return ExprError();
  1304. }
  1305. numElements = LHSType->getAs<VectorType>()->getNumElements();
  1306. unsigned numResElements = TheCall->getNumArgs() - 2;
  1307. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  1308. // with mask. If so, verify that RHS is an integer vector type with the
  1309. // same number of elts as lhs.
  1310. if (TheCall->getNumArgs() == 2) {
  1311. if (!RHSType->hasIntegerRepresentation() ||
  1312. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  1313. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1314. << SourceRange(TheCall->getArg(1)->getLocStart(),
  1315. TheCall->getArg(1)->getLocEnd());
  1316. numResElements = numElements;
  1317. }
  1318. else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  1319. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  1320. << SourceRange(TheCall->getArg(0)->getLocStart(),
  1321. TheCall->getArg(1)->getLocEnd());
  1322. return ExprError();
  1323. } else if (numElements != numResElements) {
  1324. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  1325. resType = Context.getVectorType(eltType, numResElements,
  1326. VectorType::GenericVector);
  1327. }
  1328. }
  1329. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  1330. if (TheCall->getArg(i)->isTypeDependent() ||
  1331. TheCall->getArg(i)->isValueDependent())
  1332. continue;
  1333. llvm::APSInt Result(32);
  1334. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  1335. return ExprError(Diag(TheCall->getLocStart(),
  1336. diag::err_shufflevector_nonconstant_argument)
  1337. << TheCall->getArg(i)->getSourceRange());
  1338. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  1339. return ExprError(Diag(TheCall->getLocStart(),
  1340. diag::err_shufflevector_argument_too_large)
  1341. << TheCall->getArg(i)->getSourceRange());
  1342. }
  1343. SmallVector<Expr*, 32> exprs;
  1344. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  1345. exprs.push_back(TheCall->getArg(i));
  1346. TheCall->setArg(i, 0);
  1347. }
  1348. return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
  1349. TheCall->getCallee()->getLocStart(),
  1350. TheCall->getRParenLoc()));
  1351. }
  1352. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  1353. // This is declared to take (const void*, ...) and can take two
  1354. // optional constant int args.
  1355. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  1356. unsigned NumArgs = TheCall->getNumArgs();
  1357. if (NumArgs > 3)
  1358. return Diag(TheCall->getLocEnd(),
  1359. diag::err_typecheck_call_too_many_args_at_most)
  1360. << 0 /*function call*/ << 3 << NumArgs
  1361. << TheCall->getSourceRange();
  1362. // Argument 0 is checked for us and the remaining arguments must be
  1363. // constant integers.
  1364. for (unsigned i = 1; i != NumArgs; ++i) {
  1365. Expr *Arg = TheCall->getArg(i);
  1366. // We can't check the value of a dependent argument.
  1367. if (Arg->isTypeDependent() || Arg->isValueDependent())
  1368. continue;
  1369. llvm::APSInt Result;
  1370. if (SemaBuiltinConstantArg(TheCall, i, Result))
  1371. return true;
  1372. // FIXME: gcc issues a warning and rewrites these to 0. These
  1373. // seems especially odd for the third argument since the default
  1374. // is 3.
  1375. if (i == 1) {
  1376. if (Result.getLimitedValue() > 1)
  1377. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1378. << "0" << "1" << Arg->getSourceRange();
  1379. } else {
  1380. if (Result.getLimitedValue() > 3)
  1381. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1382. << "0" << "3" << Arg->getSourceRange();
  1383. }
  1384. }
  1385. return false;
  1386. }
  1387. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  1388. /// TheCall is a constant expression.
  1389. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  1390. llvm::APSInt &Result) {
  1391. Expr *Arg = TheCall->getArg(ArgNum);
  1392. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  1393. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  1394. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  1395. if (!Arg->isIntegerConstantExpr(Result, Context))
  1396. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  1397. << FDecl->getDeclName() << Arg->getSourceRange();
  1398. return false;
  1399. }
  1400. /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
  1401. /// int type). This simply type checks that type is one of the defined
  1402. /// constants (0-3).
  1403. // For compatibility check 0-3, llvm only handles 0 and 2.
  1404. bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
  1405. llvm::APSInt Result;
  1406. // We can't check the value of a dependent argument.
  1407. if (TheCall->getArg(1)->isTypeDependent() ||
  1408. TheCall->getArg(1)->isValueDependent())
  1409. return false;
  1410. // Check constant-ness first.
  1411. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1412. return true;
  1413. Expr *Arg = TheCall->getArg(1);
  1414. if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
  1415. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  1416. << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1417. }
  1418. return false;
  1419. }
  1420. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  1421. /// This checks that val is a constant 1.
  1422. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  1423. Expr *Arg = TheCall->getArg(1);
  1424. llvm::APSInt Result;
  1425. // TODO: This is less than ideal. Overload this to take a value.
  1426. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  1427. return true;
  1428. if (Result != 1)
  1429. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  1430. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  1431. return false;
  1432. }
  1433. // Determine if an expression is a string literal or constant string.
  1434. // If this function returns false on the arguments to a function expecting a
  1435. // format string, we will usually need to emit a warning.
  1436. // True string literals are then checked by CheckFormatString.
  1437. Sema::StringLiteralCheckType
  1438. Sema::checkFormatStringExpr(const Expr *E, Expr **Args,
  1439. unsigned NumArgs, bool HasVAListArg,
  1440. unsigned format_idx, unsigned firstDataArg,
  1441. FormatStringType Type, VariadicCallType CallType,
  1442. bool inFunctionCall) {
  1443. tryAgain:
  1444. if (E->isTypeDependent() || E->isValueDependent())
  1445. return SLCT_NotALiteral;
  1446. E = E->IgnoreParenCasts();
  1447. if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
  1448. // Technically -Wformat-nonliteral does not warn about this case.
  1449. // The behavior of printf and friends in this case is implementation
  1450. // dependent. Ideally if the format string cannot be null then
  1451. // it should have a 'nonnull' attribute in the function prototype.
  1452. return SLCT_CheckedLiteral;
  1453. switch (E->getStmtClass()) {
  1454. case Stmt::BinaryConditionalOperatorClass:
  1455. case Stmt::ConditionalOperatorClass: {
  1456. // The expression is a literal if both sub-expressions were, and it was
  1457. // completely checked only if both sub-expressions were checked.
  1458. const AbstractConditionalOperator *C =
  1459. cast<AbstractConditionalOperator>(E);
  1460. StringLiteralCheckType Left =
  1461. checkFormatStringExpr(C->getTrueExpr(), Args, NumArgs,
  1462. HasVAListArg, format_idx, firstDataArg,
  1463. Type, CallType, inFunctionCall);
  1464. if (Left == SLCT_NotALiteral)
  1465. return SLCT_NotALiteral;
  1466. StringLiteralCheckType Right =
  1467. checkFormatStringExpr(C->getFalseExpr(), Args, NumArgs,
  1468. HasVAListArg, format_idx, firstDataArg,
  1469. Type, CallType, inFunctionCall);
  1470. return Left < Right ? Left : Right;
  1471. }
  1472. case Stmt::ImplicitCastExprClass: {
  1473. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  1474. goto tryAgain;
  1475. }
  1476. case Stmt::OpaqueValueExprClass:
  1477. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  1478. E = src;
  1479. goto tryAgain;
  1480. }
  1481. return SLCT_NotALiteral;
  1482. case Stmt::PredefinedExprClass:
  1483. // While __func__, etc., are technically not string literals, they
  1484. // cannot contain format specifiers and thus are not a security
  1485. // liability.
  1486. return SLCT_UncheckedLiteral;
  1487. case Stmt::DeclRefExprClass: {
  1488. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  1489. // As an exception, do not flag errors for variables binding to
  1490. // const string literals.
  1491. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  1492. bool isConstant = false;
  1493. QualType T = DR->getType();
  1494. if (const ArrayType *AT = Context.getAsArrayType(T)) {
  1495. isConstant = AT->getElementType().isConstant(Context);
  1496. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  1497. isConstant = T.isConstant(Context) &&
  1498. PT->getPointeeType().isConstant(Context);
  1499. } else if (T->isObjCObjectPointerType()) {
  1500. // In ObjC, there is usually no "const ObjectPointer" type,
  1501. // so don't check if the pointee type is constant.
  1502. isConstant = T.isConstant(Context);
  1503. }
  1504. if (isConstant) {
  1505. if (const Expr *Init = VD->getAnyInitializer()) {
  1506. // Look through initializers like const char c[] = { "foo" }
  1507. if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
  1508. if (InitList->isStringLiteralInit())
  1509. Init = InitList->getInit(0)->IgnoreParenImpCasts();
  1510. }
  1511. return checkFormatStringExpr(Init, Args, NumArgs,
  1512. HasVAListArg, format_idx,
  1513. firstDataArg, Type, CallType,
  1514. /*inFunctionCall*/false);
  1515. }
  1516. }
  1517. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  1518. // special check to see if the format string is a function parameter
  1519. // of the function calling the printf function. If the function
  1520. // has an attribute indicating it is a printf-like function, then we
  1521. // should suppress warnings concerning non-literals being used in a call
  1522. // to a vprintf function. For example:
  1523. //
  1524. // void
  1525. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  1526. // va_list ap;
  1527. // va_start(ap, fmt);
  1528. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  1529. // ...
  1530. //
  1531. if (HasVAListArg) {
  1532. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
  1533. if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
  1534. int PVIndex = PV->getFunctionScopeIndex() + 1;
  1535. for (specific_attr_iterator<FormatAttr>
  1536. i = ND->specific_attr_begin<FormatAttr>(),
  1537. e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
  1538. FormatAttr *PVFormat = *i;
  1539. // adjust for implicit parameter
  1540. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1541. if (MD->isInstance())
  1542. ++PVIndex;
  1543. // We also check if the formats are compatible.
  1544. // We can't pass a 'scanf' string to a 'printf' function.
  1545. if (PVIndex == PVFormat->getFormatIdx() &&
  1546. Type == GetFormatStringType(PVFormat))
  1547. return SLCT_UncheckedLiteral;
  1548. }
  1549. }
  1550. }
  1551. }
  1552. }
  1553. return SLCT_NotALiteral;
  1554. }
  1555. case Stmt::CallExprClass:
  1556. case Stmt::CXXMemberCallExprClass: {
  1557. const CallExpr *CE = cast<CallExpr>(E);
  1558. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
  1559. if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
  1560. unsigned ArgIndex = FA->getFormatIdx();
  1561. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
  1562. if (MD->isInstance())
  1563. --ArgIndex;
  1564. const Expr *Arg = CE->getArg(ArgIndex - 1);
  1565. return checkFormatStringExpr(Arg, Args, NumArgs,
  1566. HasVAListArg, format_idx, firstDataArg,
  1567. Type, CallType, inFunctionCall);
  1568. } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  1569. unsigned BuiltinID = FD->getBuiltinID();
  1570. if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
  1571. BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
  1572. const Expr *Arg = CE->getArg(0);
  1573. return checkFormatStringExpr(Arg, Args, NumArgs,
  1574. HasVAListArg, format_idx,
  1575. firstDataArg, Type, CallType,
  1576. inFunctionCall);
  1577. }
  1578. }
  1579. }
  1580. return SLCT_NotALiteral;
  1581. }
  1582. case Stmt::ObjCStringLiteralClass:
  1583. case Stmt::StringLiteralClass: {
  1584. const StringLiteral *StrE = NULL;
  1585. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  1586. StrE = ObjCFExpr->getString();
  1587. else
  1588. StrE = cast<StringLiteral>(E);
  1589. if (StrE) {
  1590. CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
  1591. firstDataArg, Type, inFunctionCall, CallType);
  1592. return SLCT_CheckedLiteral;
  1593. }
  1594. return SLCT_NotALiteral;
  1595. }
  1596. default:
  1597. return SLCT_NotALiteral;
  1598. }
  1599. }
  1600. void
  1601. Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
  1602. const Expr * const *ExprArgs,
  1603. SourceLocation CallSiteLoc) {
  1604. for (NonNullAttr::args_iterator i = NonNull->args_begin(),
  1605. e = NonNull->args_end();
  1606. i != e; ++i) {
  1607. const Expr *ArgExpr = ExprArgs[*i];
  1608. if (ArgExpr->isNullPointerConstant(Context,
  1609. Expr::NPC_ValueDependentIsNotNull))
  1610. Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  1611. }
  1612. }
  1613. Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
  1614. return llvm::StringSwitch<FormatStringType>(Format->getType())
  1615. .Case("scanf", FST_Scanf)
  1616. .Cases("printf", "printf0", FST_Printf)
  1617. .Cases("NSString", "CFString", FST_NSString)
  1618. .Case("strftime", FST_Strftime)
  1619. .Case("strfmon", FST_Strfmon)
  1620. .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
  1621. .Default(FST_Unknown);
  1622. }
  1623. /// CheckFormatArguments - Check calls to printf and scanf (and similar
  1624. /// functions) for correct use of format strings.
  1625. /// Returns true if a format string has been fully checked.
  1626. bool Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
  1627. unsigned NumArgs, bool IsCXXMember,
  1628. VariadicCallType CallType,
  1629. SourceLocation Loc, SourceRange Range) {
  1630. FormatStringInfo FSI;
  1631. if (getFormatStringInfo(Format, IsCXXMember, &FSI))
  1632. return CheckFormatArguments(Args, NumArgs, FSI.HasVAListArg, FSI.FormatIdx,
  1633. FSI.FirstDataArg, GetFormatStringType(Format),
  1634. CallType, Loc, Range);
  1635. return false;
  1636. }
  1637. bool Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
  1638. bool HasVAListArg, unsigned format_idx,
  1639. unsigned firstDataArg, FormatStringType Type,
  1640. VariadicCallType CallType,
  1641. SourceLocation Loc, SourceRange Range) {
  1642. // CHECK: printf/scanf-like function is called with no format string.
  1643. if (format_idx >= NumArgs) {
  1644. Diag(Loc, diag::warn_missing_format_string) << Range;
  1645. return false;
  1646. }
  1647. const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
  1648. // CHECK: format string is not a string literal.
  1649. //
  1650. // Dynamically generated format strings are difficult to
  1651. // automatically vet at compile time. Requiring that format strings
  1652. // are string literals: (1) permits the checking of format strings by
  1653. // the compiler and thereby (2) can practically remove the source of
  1654. // many format string exploits.
  1655. // Format string can be either ObjC string (e.g. @"%d") or
  1656. // C string (e.g. "%d")
  1657. // ObjC string uses the same format specifiers as C string, so we can use
  1658. // the same format string checking logic for both ObjC and C strings.
  1659. StringLiteralCheckType CT =
  1660. checkFormatStringExpr(OrigFormatExpr, Args, NumArgs, HasVAListArg,
  1661. format_idx, firstDataArg, Type, CallType);
  1662. if (CT != SLCT_NotALiteral)
  1663. // Literal format string found, check done!
  1664. return CT == SLCT_CheckedLiteral;
  1665. // Strftime is particular as it always uses a single 'time' argument,
  1666. // so it is safe to pass a non-literal string.
  1667. if (Type == FST_Strftime)
  1668. return false;
  1669. // Do not emit diag when the string param is a macro expansion and the
  1670. // format is either NSString or CFString. This is a hack to prevent
  1671. // diag when using the NSLocalizedString and CFCopyLocalizedString macros
  1672. // which are usually used in place of NS and CF string literals.
  1673. if (Type == FST_NSString &&
  1674. SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
  1675. return false;
  1676. // If there are no arguments specified, warn with -Wformat-security, otherwise
  1677. // warn only with -Wformat-nonliteral.
  1678. if (NumArgs == format_idx+1)
  1679. Diag(Args[format_idx]->getLocStart(),
  1680. diag::warn_format_nonliteral_noargs)
  1681. << OrigFormatExpr->getSourceRange();
  1682. else
  1683. Diag(Args[format_idx]->getLocStart(),
  1684. diag::warn_format_nonliteral)
  1685. << OrigFormatExpr->getSourceRange();
  1686. return false;
  1687. }
  1688. namespace {
  1689. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  1690. protected:
  1691. Sema &S;
  1692. const StringLiteral *FExpr;
  1693. const Expr *OrigFormatExpr;
  1694. const unsigned FirstDataArg;
  1695. const unsigned NumDataArgs;
  1696. const char *Beg; // Start of format string.
  1697. const bool HasVAListArg;
  1698. const Expr * const *Args;
  1699. const unsigned NumArgs;
  1700. unsigned FormatIdx;
  1701. llvm::BitVector CoveredArgs;
  1702. bool usesPositionalArgs;
  1703. bool atFirstArg;
  1704. bool inFunctionCall;
  1705. Sema::VariadicCallType CallType;
  1706. public:
  1707. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  1708. const Expr *origFormatExpr, unsigned firstDataArg,
  1709. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  1710. Expr **args, unsigned numArgs,
  1711. unsigned formatIdx, bool inFunctionCall,
  1712. Sema::VariadicCallType callType)
  1713. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  1714. FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
  1715. Beg(beg), HasVAListArg(hasVAListArg),
  1716. Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
  1717. usesPositionalArgs(false), atFirstArg(true),
  1718. inFunctionCall(inFunctionCall), CallType(callType) {
  1719. CoveredArgs.resize(numDataArgs);
  1720. CoveredArgs.reset();
  1721. }
  1722. void DoneProcessing();
  1723. void HandleIncompleteSpecifier(const char *startSpecifier,
  1724. unsigned specifierLen);
  1725. void HandleInvalidLengthModifier(
  1726. const analyze_format_string::FormatSpecifier &FS,
  1727. const analyze_format_string::ConversionSpecifier &CS,
  1728. const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
  1729. void HandleNonStandardLengthModifier(
  1730. const analyze_format_string::FormatSpecifier &FS,
  1731. const char *startSpecifier, unsigned specifierLen);
  1732. void HandleNonStandardConversionSpecifier(
  1733. const analyze_format_string::ConversionSpecifier &CS,
  1734. const char *startSpecifier, unsigned specifierLen);
  1735. virtual void HandlePosition(const char *startPos, unsigned posLen);
  1736. virtual void HandleInvalidPosition(const char *startSpecifier,
  1737. unsigned specifierLen,
  1738. analyze_format_string::PositionContext p);
  1739. virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
  1740. void HandleNullChar(const char *nullCharacter);
  1741. template <typename Range>
  1742. static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
  1743. const Expr *ArgumentExpr,
  1744. PartialDiagnostic PDiag,
  1745. SourceLocation StringLoc,
  1746. bool IsStringLocation, Range StringRange,
  1747. ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
  1748. protected:
  1749. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  1750. const char *startSpec,
  1751. unsigned specifierLen,
  1752. const char *csStart, unsigned csLen);
  1753. void HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1754. const char *startSpec,
  1755. unsigned specifierLen);
  1756. SourceRange getFormatStringRange();
  1757. CharSourceRange getSpecifierRange(const char *startSpecifier,
  1758. unsigned specifierLen);
  1759. SourceLocation getLocationOfByte(const char *x);
  1760. const Expr *getDataArg(unsigned i) const;
  1761. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  1762. const analyze_format_string::ConversionSpecifier &CS,
  1763. const char *startSpecifier, unsigned specifierLen,
  1764. unsigned argIndex);
  1765. template <typename Range>
  1766. void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
  1767. bool IsStringLocation, Range StringRange,
  1768. ArrayRef<FixItHint> Fixit = ArrayRef<FixItHint>());
  1769. void CheckPositionalAndNonpositionalArgs(
  1770. const analyze_format_string::FormatSpecifier *FS);
  1771. };
  1772. }
  1773. SourceRange CheckFormatHandler::getFormatStringRange() {
  1774. return OrigFormatExpr->getSourceRange();
  1775. }
  1776. CharSourceRange CheckFormatHandler::
  1777. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  1778. SourceLocation Start = getLocationOfByte(startSpecifier);
  1779. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  1780. // Advance the end SourceLocation by one due to half-open ranges.
  1781. End = End.getLocWithOffset(1);
  1782. return CharSourceRange::getCharRange(Start, End);
  1783. }
  1784. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  1785. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  1786. }
  1787. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  1788. unsigned specifierLen){
  1789. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
  1790. getLocationOfByte(startSpecifier),
  1791. /*IsStringLocation*/true,
  1792. getSpecifierRange(startSpecifier, specifierLen));
  1793. }
  1794. void CheckFormatHandler::HandleInvalidLengthModifier(
  1795. const analyze_format_string::FormatSpecifier &FS,
  1796. const analyze_format_string::ConversionSpecifier &CS,
  1797. const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
  1798. using namespace analyze_format_string;
  1799. const LengthModifier &LM = FS.getLengthModifier();
  1800. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  1801. // See if we know how to fix this length modifier.
  1802. llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  1803. if (FixedLM) {
  1804. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  1805. getLocationOfByte(LM.getStart()),
  1806. /*IsStringLocation*/true,
  1807. getSpecifierRange(startSpecifier, specifierLen));
  1808. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  1809. << FixedLM->toString()
  1810. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  1811. } else {
  1812. FixItHint Hint;
  1813. if (DiagID == diag::warn_format_nonsensical_length)
  1814. Hint = FixItHint::CreateRemoval(LMRange);
  1815. EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
  1816. getLocationOfByte(LM.getStart()),
  1817. /*IsStringLocation*/true,
  1818. getSpecifierRange(startSpecifier, specifierLen),
  1819. Hint);
  1820. }
  1821. }
  1822. void CheckFormatHandler::HandleNonStandardLengthModifier(
  1823. const analyze_format_string::FormatSpecifier &FS,
  1824. const char *startSpecifier, unsigned specifierLen) {
  1825. using namespace analyze_format_string;
  1826. const LengthModifier &LM = FS.getLengthModifier();
  1827. CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
  1828. // See if we know how to fix this length modifier.
  1829. llvm::Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
  1830. if (FixedLM) {
  1831. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  1832. << LM.toString() << 0,
  1833. getLocationOfByte(LM.getStart()),
  1834. /*IsStringLocation*/true,
  1835. getSpecifierRange(startSpecifier, specifierLen));
  1836. S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
  1837. << FixedLM->toString()
  1838. << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
  1839. } else {
  1840. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  1841. << LM.toString() << 0,
  1842. getLocationOfByte(LM.getStart()),
  1843. /*IsStringLocation*/true,
  1844. getSpecifierRange(startSpecifier, specifierLen));
  1845. }
  1846. }
  1847. void CheckFormatHandler::HandleNonStandardConversionSpecifier(
  1848. const analyze_format_string::ConversionSpecifier &CS,
  1849. const char *startSpecifier, unsigned specifierLen) {
  1850. using namespace analyze_format_string;
  1851. // See if we know how to fix this conversion specifier.
  1852. llvm::Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
  1853. if (FixedCS) {
  1854. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  1855. << CS.toString() << /*conversion specifier*/1,
  1856. getLocationOfByte(CS.getStart()),
  1857. /*IsStringLocation*/true,
  1858. getSpecifierRange(startSpecifier, specifierLen));
  1859. CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
  1860. S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
  1861. << FixedCS->toString()
  1862. << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
  1863. } else {
  1864. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
  1865. << CS.toString() << /*conversion specifier*/1,
  1866. getLocationOfByte(CS.getStart()),
  1867. /*IsStringLocation*/true,
  1868. getSpecifierRange(startSpecifier, specifierLen));
  1869. }
  1870. }
  1871. void CheckFormatHandler::HandlePosition(const char *startPos,
  1872. unsigned posLen) {
  1873. EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
  1874. getLocationOfByte(startPos),
  1875. /*IsStringLocation*/true,
  1876. getSpecifierRange(startPos, posLen));
  1877. }
  1878. void
  1879. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  1880. analyze_format_string::PositionContext p) {
  1881. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
  1882. << (unsigned) p,
  1883. getLocationOfByte(startPos), /*IsStringLocation*/true,
  1884. getSpecifierRange(startPos, posLen));
  1885. }
  1886. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  1887. unsigned posLen) {
  1888. EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
  1889. getLocationOfByte(startPos),
  1890. /*IsStringLocation*/true,
  1891. getSpecifierRange(startPos, posLen));
  1892. }
  1893. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  1894. if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
  1895. // The presence of a null character is likely an error.
  1896. EmitFormatDiagnostic(
  1897. S.PDiag(diag::warn_printf_format_string_contains_null_char),
  1898. getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
  1899. getFormatStringRange());
  1900. }
  1901. }
  1902. // Note that this may return NULL if there was an error parsing or building
  1903. // one of the argument expressions.
  1904. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  1905. return Args[FirstDataArg + i];
  1906. }
  1907. void CheckFormatHandler::DoneProcessing() {
  1908. // Does the number of data arguments exceed the number of
  1909. // format conversions in the format string?
  1910. if (!HasVAListArg) {
  1911. // Find any arguments that weren't covered.
  1912. CoveredArgs.flip();
  1913. signed notCoveredArg = CoveredArgs.find_first();
  1914. if (notCoveredArg >= 0) {
  1915. assert((unsigned)notCoveredArg < NumDataArgs);
  1916. if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
  1917. SourceLocation Loc = E->getLocStart();
  1918. if (!S.getSourceManager().isInSystemMacro(Loc)) {
  1919. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
  1920. Loc, /*IsStringLocation*/false,
  1921. getFormatStringRange());
  1922. }
  1923. }
  1924. }
  1925. }
  1926. }
  1927. bool
  1928. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  1929. SourceLocation Loc,
  1930. const char *startSpec,
  1931. unsigned specifierLen,
  1932. const char *csStart,
  1933. unsigned csLen) {
  1934. bool keepGoing = true;
  1935. if (argIndex < NumDataArgs) {
  1936. // Consider the argument coverered, even though the specifier doesn't
  1937. // make sense.
  1938. CoveredArgs.set(argIndex);
  1939. }
  1940. else {
  1941. // If argIndex exceeds the number of data arguments we
  1942. // don't issue a warning because that is just a cascade of warnings (and
  1943. // they may have intended '%%' anyway). We don't want to continue processing
  1944. // the format string after this point, however, as we will like just get
  1945. // gibberish when trying to match arguments.
  1946. keepGoing = false;
  1947. }
  1948. EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
  1949. << StringRef(csStart, csLen),
  1950. Loc, /*IsStringLocation*/true,
  1951. getSpecifierRange(startSpec, specifierLen));
  1952. return keepGoing;
  1953. }
  1954. void
  1955. CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
  1956. const char *startSpec,
  1957. unsigned specifierLen) {
  1958. EmitFormatDiagnostic(
  1959. S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
  1960. Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
  1961. }
  1962. bool
  1963. CheckFormatHandler::CheckNumArgs(
  1964. const analyze_format_string::FormatSpecifier &FS,
  1965. const analyze_format_string::ConversionSpecifier &CS,
  1966. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  1967. if (argIndex >= NumDataArgs) {
  1968. PartialDiagnostic PDiag = FS.usesPositionalArg()
  1969. ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
  1970. << (argIndex+1) << NumDataArgs)
  1971. : S.PDiag(diag::warn_printf_insufficient_data_args);
  1972. EmitFormatDiagnostic(
  1973. PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
  1974. getSpecifierRange(startSpecifier, specifierLen));
  1975. return false;
  1976. }
  1977. return true;
  1978. }
  1979. template<typename Range>
  1980. void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
  1981. SourceLocation Loc,
  1982. bool IsStringLocation,
  1983. Range StringRange,
  1984. ArrayRef<FixItHint> FixIt) {
  1985. EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
  1986. Loc, IsStringLocation, StringRange, FixIt);
  1987. }
  1988. /// \brief If the format string is not within the funcion call, emit a note
  1989. /// so that the function call and string are in diagnostic messages.
  1990. ///
  1991. /// \param InFunctionCall if true, the format string is within the function
  1992. /// call and only one diagnostic message will be produced. Otherwise, an
  1993. /// extra note will be emitted pointing to location of the format string.
  1994. ///
  1995. /// \param ArgumentExpr the expression that is passed as the format string
  1996. /// argument in the function call. Used for getting locations when two
  1997. /// diagnostics are emitted.
  1998. ///
  1999. /// \param PDiag the callee should already have provided any strings for the
  2000. /// diagnostic message. This function only adds locations and fixits
  2001. /// to diagnostics.
  2002. ///
  2003. /// \param Loc primary location for diagnostic. If two diagnostics are
  2004. /// required, one will be at Loc and a new SourceLocation will be created for
  2005. /// the other one.
  2006. ///
  2007. /// \param IsStringLocation if true, Loc points to the format string should be
  2008. /// used for the note. Otherwise, Loc points to the argument list and will
  2009. /// be used with PDiag.
  2010. ///
  2011. /// \param StringRange some or all of the string to highlight. This is
  2012. /// templated so it can accept either a CharSourceRange or a SourceRange.
  2013. ///
  2014. /// \param FixIt optional fix it hint for the format string.
  2015. template<typename Range>
  2016. void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
  2017. const Expr *ArgumentExpr,
  2018. PartialDiagnostic PDiag,
  2019. SourceLocation Loc,
  2020. bool IsStringLocation,
  2021. Range StringRange,
  2022. ArrayRef<FixItHint> FixIt) {
  2023. if (InFunctionCall) {
  2024. const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
  2025. D << StringRange;
  2026. for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
  2027. I != E; ++I) {
  2028. D << *I;
  2029. }
  2030. } else {
  2031. S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
  2032. << ArgumentExpr->getSourceRange();
  2033. const Sema::SemaDiagnosticBuilder &Note =
  2034. S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
  2035. diag::note_format_string_defined);
  2036. Note << StringRange;
  2037. for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
  2038. I != E; ++I) {
  2039. Note << *I;
  2040. }
  2041. }
  2042. }
  2043. //===--- CHECK: Printf format string checking ------------------------------===//
  2044. namespace {
  2045. class CheckPrintfHandler : public CheckFormatHandler {
  2046. bool ObjCContext;
  2047. public:
  2048. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  2049. const Expr *origFormatExpr, unsigned firstDataArg,
  2050. unsigned numDataArgs, bool isObjC,
  2051. const char *beg, bool hasVAListArg,
  2052. Expr **Args, unsigned NumArgs,
  2053. unsigned formatIdx, bool inFunctionCall,
  2054. Sema::VariadicCallType CallType)
  2055. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  2056. numDataArgs, beg, hasVAListArg, Args, NumArgs,
  2057. formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
  2058. {}
  2059. bool HandleInvalidPrintfConversionSpecifier(
  2060. const analyze_printf::PrintfSpecifier &FS,
  2061. const char *startSpecifier,
  2062. unsigned specifierLen);
  2063. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  2064. const char *startSpecifier,
  2065. unsigned specifierLen);
  2066. bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2067. const char *StartSpecifier,
  2068. unsigned SpecifierLen,
  2069. const Expr *E);
  2070. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  2071. const char *startSpecifier, unsigned specifierLen);
  2072. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  2073. const analyze_printf::OptionalAmount &Amt,
  2074. unsigned type,
  2075. const char *startSpecifier, unsigned specifierLen);
  2076. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2077. const analyze_printf::OptionalFlag &flag,
  2078. const char *startSpecifier, unsigned specifierLen);
  2079. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  2080. const analyze_printf::OptionalFlag &ignoredFlag,
  2081. const analyze_printf::OptionalFlag &flag,
  2082. const char *startSpecifier, unsigned specifierLen);
  2083. bool checkForCStrMembers(const analyze_printf::ArgType &AT,
  2084. const Expr *E, const CharSourceRange &CSR);
  2085. };
  2086. }
  2087. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  2088. const analyze_printf::PrintfSpecifier &FS,
  2089. const char *startSpecifier,
  2090. unsigned specifierLen) {
  2091. const analyze_printf::PrintfConversionSpecifier &CS =
  2092. FS.getConversionSpecifier();
  2093. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2094. getLocationOfByte(CS.getStart()),
  2095. startSpecifier, specifierLen,
  2096. CS.getStart(), CS.getLength());
  2097. }
  2098. bool CheckPrintfHandler::HandleAmount(
  2099. const analyze_format_string::OptionalAmount &Amt,
  2100. unsigned k, const char *startSpecifier,
  2101. unsigned specifierLen) {
  2102. if (Amt.hasDataArgument()) {
  2103. if (!HasVAListArg) {
  2104. unsigned argIndex = Amt.getArgIndex();
  2105. if (argIndex >= NumDataArgs) {
  2106. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
  2107. << k,
  2108. getLocationOfByte(Amt.getStart()),
  2109. /*IsStringLocation*/true,
  2110. getSpecifierRange(startSpecifier, specifierLen));
  2111. // Don't do any more checking. We will just emit
  2112. // spurious errors.
  2113. return false;
  2114. }
  2115. // Type check the data argument. It should be an 'int'.
  2116. // Although not in conformance with C99, we also allow the argument to be
  2117. // an 'unsigned int' as that is a reasonably safe case. GCC also
  2118. // doesn't emit a warning for that case.
  2119. CoveredArgs.set(argIndex);
  2120. const Expr *Arg = getDataArg(argIndex);
  2121. if (!Arg)
  2122. return false;
  2123. QualType T = Arg->getType();
  2124. const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
  2125. assert(AT.isValid());
  2126. if (!AT.matchesType(S.Context, T)) {
  2127. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
  2128. << k << AT.getRepresentativeTypeName(S.Context)
  2129. << T << Arg->getSourceRange(),
  2130. getLocationOfByte(Amt.getStart()),
  2131. /*IsStringLocation*/true,
  2132. getSpecifierRange(startSpecifier, specifierLen));
  2133. // Don't do any more checking. We will just emit
  2134. // spurious errors.
  2135. return false;
  2136. }
  2137. }
  2138. }
  2139. return true;
  2140. }
  2141. void CheckPrintfHandler::HandleInvalidAmount(
  2142. const analyze_printf::PrintfSpecifier &FS,
  2143. const analyze_printf::OptionalAmount &Amt,
  2144. unsigned type,
  2145. const char *startSpecifier,
  2146. unsigned specifierLen) {
  2147. const analyze_printf::PrintfConversionSpecifier &CS =
  2148. FS.getConversionSpecifier();
  2149. FixItHint fixit =
  2150. Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
  2151. ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  2152. Amt.getConstantLength()))
  2153. : FixItHint();
  2154. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
  2155. << type << CS.toString(),
  2156. getLocationOfByte(Amt.getStart()),
  2157. /*IsStringLocation*/true,
  2158. getSpecifierRange(startSpecifier, specifierLen),
  2159. fixit);
  2160. }
  2161. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  2162. const analyze_printf::OptionalFlag &flag,
  2163. const char *startSpecifier,
  2164. unsigned specifierLen) {
  2165. // Warn about pointless flag with a fixit removal.
  2166. const analyze_printf::PrintfConversionSpecifier &CS =
  2167. FS.getConversionSpecifier();
  2168. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
  2169. << flag.toString() << CS.toString(),
  2170. getLocationOfByte(flag.getPosition()),
  2171. /*IsStringLocation*/true,
  2172. getSpecifierRange(startSpecifier, specifierLen),
  2173. FixItHint::CreateRemoval(
  2174. getSpecifierRange(flag.getPosition(), 1)));
  2175. }
  2176. void CheckPrintfHandler::HandleIgnoredFlag(
  2177. const analyze_printf::PrintfSpecifier &FS,
  2178. const analyze_printf::OptionalFlag &ignoredFlag,
  2179. const analyze_printf::OptionalFlag &flag,
  2180. const char *startSpecifier,
  2181. unsigned specifierLen) {
  2182. // Warn about ignored flag with a fixit removal.
  2183. EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
  2184. << ignoredFlag.toString() << flag.toString(),
  2185. getLocationOfByte(ignoredFlag.getPosition()),
  2186. /*IsStringLocation*/true,
  2187. getSpecifierRange(startSpecifier, specifierLen),
  2188. FixItHint::CreateRemoval(
  2189. getSpecifierRange(ignoredFlag.getPosition(), 1)));
  2190. }
  2191. // Determines if the specified is a C++ class or struct containing
  2192. // a member with the specified name and kind (e.g. a CXXMethodDecl named
  2193. // "c_str()").
  2194. template<typename MemberKind>
  2195. static llvm::SmallPtrSet<MemberKind*, 1>
  2196. CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
  2197. const RecordType *RT = Ty->getAs<RecordType>();
  2198. llvm::SmallPtrSet<MemberKind*, 1> Results;
  2199. if (!RT)
  2200. return Results;
  2201. const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
  2202. if (!RD)
  2203. return Results;
  2204. LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
  2205. Sema::LookupMemberName);
  2206. // We just need to include all members of the right kind turned up by the
  2207. // filter, at this point.
  2208. if (S.LookupQualifiedName(R, RT->getDecl()))
  2209. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2210. NamedDecl *decl = (*I)->getUnderlyingDecl();
  2211. if (MemberKind *FK = dyn_cast<MemberKind>(decl))
  2212. Results.insert(FK);
  2213. }
  2214. return Results;
  2215. }
  2216. // Check if a (w)string was passed when a (w)char* was needed, and offer a
  2217. // better diagnostic if so. AT is assumed to be valid.
  2218. // Returns true when a c_str() conversion method is found.
  2219. bool CheckPrintfHandler::checkForCStrMembers(
  2220. const analyze_printf::ArgType &AT, const Expr *E,
  2221. const CharSourceRange &CSR) {
  2222. typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
  2223. MethodSet Results =
  2224. CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
  2225. for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
  2226. MI != ME; ++MI) {
  2227. const CXXMethodDecl *Method = *MI;
  2228. if (Method->getNumParams() == 0 &&
  2229. AT.matchesType(S.Context, Method->getResultType())) {
  2230. // FIXME: Suggest parens if the expression needs them.
  2231. SourceLocation EndLoc =
  2232. S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
  2233. S.Diag(E->getLocStart(), diag::note_printf_c_str)
  2234. << "c_str()"
  2235. << FixItHint::CreateInsertion(EndLoc, ".c_str()");
  2236. return true;
  2237. }
  2238. }
  2239. return false;
  2240. }
  2241. bool
  2242. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  2243. &FS,
  2244. const char *startSpecifier,
  2245. unsigned specifierLen) {
  2246. using namespace analyze_format_string;
  2247. using namespace analyze_printf;
  2248. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  2249. if (FS.consumesDataArgument()) {
  2250. if (atFirstArg) {
  2251. atFirstArg = false;
  2252. usesPositionalArgs = FS.usesPositionalArg();
  2253. }
  2254. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2255. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2256. startSpecifier, specifierLen);
  2257. return false;
  2258. }
  2259. }
  2260. // First check if the field width, precision, and conversion specifier
  2261. // have matching data arguments.
  2262. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  2263. startSpecifier, specifierLen)) {
  2264. return false;
  2265. }
  2266. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  2267. startSpecifier, specifierLen)) {
  2268. return false;
  2269. }
  2270. if (!CS.consumesDataArgument()) {
  2271. // FIXME: Technically specifying a precision or field width here
  2272. // makes no sense. Worth issuing a warning at some point.
  2273. return true;
  2274. }
  2275. // Consume the argument.
  2276. unsigned argIndex = FS.getArgIndex();
  2277. if (argIndex < NumDataArgs) {
  2278. // The check to see if the argIndex is valid will come later.
  2279. // We set the bit here because we may exit early from this
  2280. // function if we encounter some other error.
  2281. CoveredArgs.set(argIndex);
  2282. }
  2283. // Check for using an Objective-C specific conversion specifier
  2284. // in a non-ObjC literal.
  2285. if (!ObjCContext && CS.isObjCArg()) {
  2286. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  2287. specifierLen);
  2288. }
  2289. // Check for invalid use of field width
  2290. if (!FS.hasValidFieldWidth()) {
  2291. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  2292. startSpecifier, specifierLen);
  2293. }
  2294. // Check for invalid use of precision
  2295. if (!FS.hasValidPrecision()) {
  2296. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  2297. startSpecifier, specifierLen);
  2298. }
  2299. // Check each flag does not conflict with any other component.
  2300. if (!FS.hasValidThousandsGroupingPrefix())
  2301. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  2302. if (!FS.hasValidLeadingZeros())
  2303. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  2304. if (!FS.hasValidPlusPrefix())
  2305. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  2306. if (!FS.hasValidSpacePrefix())
  2307. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  2308. if (!FS.hasValidAlternativeForm())
  2309. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  2310. if (!FS.hasValidLeftJustified())
  2311. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  2312. // Check that flags are not ignored by another flag
  2313. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  2314. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  2315. startSpecifier, specifierLen);
  2316. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  2317. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  2318. startSpecifier, specifierLen);
  2319. // Check the length modifier is valid with the given conversion specifier.
  2320. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  2321. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2322. diag::warn_format_nonsensical_length);
  2323. else if (!FS.hasStandardLengthModifier())
  2324. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  2325. else if (!FS.hasStandardLengthConversionCombination())
  2326. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2327. diag::warn_format_non_standard_conversion_spec);
  2328. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2329. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2330. // The remaining checks depend on the data arguments.
  2331. if (HasVAListArg)
  2332. return true;
  2333. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2334. return false;
  2335. const Expr *Arg = getDataArg(argIndex);
  2336. if (!Arg)
  2337. return true;
  2338. return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
  2339. }
  2340. static bool requiresParensToAddCast(const Expr *E) {
  2341. // FIXME: We should have a general way to reason about operator
  2342. // precedence and whether parens are actually needed here.
  2343. // Take care of a few common cases where they aren't.
  2344. const Expr *Inside = E->IgnoreImpCasts();
  2345. if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
  2346. Inside = POE->getSyntacticForm()->IgnoreImpCasts();
  2347. switch (Inside->getStmtClass()) {
  2348. case Stmt::ArraySubscriptExprClass:
  2349. case Stmt::CallExprClass:
  2350. case Stmt::DeclRefExprClass:
  2351. case Stmt::MemberExprClass:
  2352. case Stmt::ObjCIvarRefExprClass:
  2353. case Stmt::ObjCMessageExprClass:
  2354. case Stmt::ObjCPropertyRefExprClass:
  2355. case Stmt::ParenExprClass:
  2356. case Stmt::UnaryOperatorClass:
  2357. return false;
  2358. default:
  2359. return true;
  2360. }
  2361. }
  2362. bool
  2363. CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
  2364. const char *StartSpecifier,
  2365. unsigned SpecifierLen,
  2366. const Expr *E) {
  2367. using namespace analyze_format_string;
  2368. using namespace analyze_printf;
  2369. // Now type check the data expression that matches the
  2370. // format specifier.
  2371. const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
  2372. ObjCContext);
  2373. if (!AT.isValid())
  2374. return true;
  2375. QualType IntendedTy = E->getType();
  2376. if (AT.matchesType(S.Context, IntendedTy))
  2377. return true;
  2378. // Look through argument promotions for our error message's reported type.
  2379. // This includes the integral and floating promotions, but excludes array
  2380. // and function pointer decay; seeing that an argument intended to be a
  2381. // string has type 'char [6]' is probably more confusing than 'char *'.
  2382. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2383. if (ICE->getCastKind() == CK_IntegralCast ||
  2384. ICE->getCastKind() == CK_FloatingCast) {
  2385. E = ICE->getSubExpr();
  2386. IntendedTy = E->getType();
  2387. // Check if we didn't match because of an implicit cast from a 'char'
  2388. // or 'short' to an 'int'. This is done because printf is a varargs
  2389. // function.
  2390. if (ICE->getType() == S.Context.IntTy ||
  2391. ICE->getType() == S.Context.UnsignedIntTy) {
  2392. // All further checking is done on the subexpression.
  2393. if (AT.matchesType(S.Context, IntendedTy))
  2394. return true;
  2395. }
  2396. }
  2397. }
  2398. if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
  2399. // Special-case some of Darwin's platform-independence types.
  2400. if (const TypedefType *UserTy = IntendedTy->getAs<TypedefType>()) {
  2401. StringRef Name = UserTy->getDecl()->getName();
  2402. IntendedTy = llvm::StringSwitch<QualType>(Name)
  2403. .Case("NSInteger", S.Context.LongTy)
  2404. .Case("NSUInteger", S.Context.UnsignedLongTy)
  2405. .Case("SInt32", S.Context.IntTy)
  2406. .Case("UInt32", S.Context.UnsignedIntTy)
  2407. .Default(IntendedTy);
  2408. }
  2409. }
  2410. // We may be able to offer a FixItHint if it is a supported type.
  2411. PrintfSpecifier fixedFS = FS;
  2412. bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
  2413. S.Context, ObjCContext);
  2414. if (success) {
  2415. // Get the fix string from the fixed format specifier
  2416. SmallString<16> buf;
  2417. llvm::raw_svector_ostream os(buf);
  2418. fixedFS.toString(os);
  2419. CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
  2420. if (IntendedTy != E->getType()) {
  2421. // The canonical type for formatting this value is different from the
  2422. // actual type of the expression. (This occurs, for example, with Darwin's
  2423. // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
  2424. // should be printed as 'long' for 64-bit compatibility.)
  2425. // Rather than emitting a normal format/argument mismatch, we want to
  2426. // add a cast to the recommended type (and correct the format string
  2427. // if necessary).
  2428. SmallString<16> CastBuf;
  2429. llvm::raw_svector_ostream CastFix(CastBuf);
  2430. CastFix << "(";
  2431. IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
  2432. CastFix << ")";
  2433. SmallVector<FixItHint,4> Hints;
  2434. if (!AT.matchesType(S.Context, IntendedTy))
  2435. Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
  2436. if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
  2437. // If there's already a cast present, just replace it.
  2438. SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
  2439. Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
  2440. } else if (!requiresParensToAddCast(E)) {
  2441. // If the expression has high enough precedence,
  2442. // just write the C-style cast.
  2443. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  2444. CastFix.str()));
  2445. } else {
  2446. // Otherwise, add parens around the expression as well as the cast.
  2447. CastFix << "(";
  2448. Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
  2449. CastFix.str()));
  2450. SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
  2451. Hints.push_back(FixItHint::CreateInsertion(After, ")"));
  2452. }
  2453. // We extract the name from the typedef because we don't want to show
  2454. // the underlying type in the diagnostic.
  2455. const TypedefType *UserTy = cast<TypedefType>(E->getType());
  2456. StringRef Name = UserTy->getDecl()->getName();
  2457. // Finally, emit the diagnostic.
  2458. EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
  2459. << Name << IntendedTy
  2460. << E->getSourceRange(),
  2461. E->getLocStart(), /*IsStringLocation=*/false,
  2462. SpecRange, Hints);
  2463. } else {
  2464. EmitFormatDiagnostic(
  2465. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2466. << AT.getRepresentativeTypeName(S.Context) << IntendedTy
  2467. << E->getSourceRange(),
  2468. E->getLocStart(),
  2469. /*IsStringLocation*/false,
  2470. SpecRange,
  2471. FixItHint::CreateReplacement(SpecRange, os.str()));
  2472. }
  2473. } else {
  2474. const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
  2475. SpecifierLen);
  2476. // Since the warning for passing non-POD types to variadic functions
  2477. // was deferred until now, we emit a warning for non-POD
  2478. // arguments here.
  2479. if (S.isValidVarArgType(E->getType()) == Sema::VAK_Invalid) {
  2480. unsigned DiagKind;
  2481. if (E->getType()->isObjCObjectType())
  2482. DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
  2483. else
  2484. DiagKind = diag::warn_non_pod_vararg_with_format_string;
  2485. EmitFormatDiagnostic(
  2486. S.PDiag(DiagKind)
  2487. << S.getLangOpts().CPlusPlus0x
  2488. << E->getType()
  2489. << CallType
  2490. << AT.getRepresentativeTypeName(S.Context)
  2491. << CSR
  2492. << E->getSourceRange(),
  2493. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2494. checkForCStrMembers(AT, E, CSR);
  2495. } else
  2496. EmitFormatDiagnostic(
  2497. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2498. << AT.getRepresentativeTypeName(S.Context) << E->getType()
  2499. << CSR
  2500. << E->getSourceRange(),
  2501. E->getLocStart(), /*IsStringLocation*/false, CSR);
  2502. }
  2503. return true;
  2504. }
  2505. //===--- CHECK: Scanf format string checking ------------------------------===//
  2506. namespace {
  2507. class CheckScanfHandler : public CheckFormatHandler {
  2508. public:
  2509. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  2510. const Expr *origFormatExpr, unsigned firstDataArg,
  2511. unsigned numDataArgs, const char *beg, bool hasVAListArg,
  2512. Expr **Args, unsigned NumArgs,
  2513. unsigned formatIdx, bool inFunctionCall,
  2514. Sema::VariadicCallType CallType)
  2515. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  2516. numDataArgs, beg, hasVAListArg,
  2517. Args, NumArgs, formatIdx, inFunctionCall, CallType)
  2518. {}
  2519. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  2520. const char *startSpecifier,
  2521. unsigned specifierLen);
  2522. bool HandleInvalidScanfConversionSpecifier(
  2523. const analyze_scanf::ScanfSpecifier &FS,
  2524. const char *startSpecifier,
  2525. unsigned specifierLen);
  2526. void HandleIncompleteScanList(const char *start, const char *end);
  2527. };
  2528. }
  2529. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  2530. const char *end) {
  2531. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
  2532. getLocationOfByte(end), /*IsStringLocation*/true,
  2533. getSpecifierRange(start, end - start));
  2534. }
  2535. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  2536. const analyze_scanf::ScanfSpecifier &FS,
  2537. const char *startSpecifier,
  2538. unsigned specifierLen) {
  2539. const analyze_scanf::ScanfConversionSpecifier &CS =
  2540. FS.getConversionSpecifier();
  2541. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  2542. getLocationOfByte(CS.getStart()),
  2543. startSpecifier, specifierLen,
  2544. CS.getStart(), CS.getLength());
  2545. }
  2546. bool CheckScanfHandler::HandleScanfSpecifier(
  2547. const analyze_scanf::ScanfSpecifier &FS,
  2548. const char *startSpecifier,
  2549. unsigned specifierLen) {
  2550. using namespace analyze_scanf;
  2551. using namespace analyze_format_string;
  2552. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  2553. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  2554. // be used to decide if we are using positional arguments consistently.
  2555. if (FS.consumesDataArgument()) {
  2556. if (atFirstArg) {
  2557. atFirstArg = false;
  2558. usesPositionalArgs = FS.usesPositionalArg();
  2559. }
  2560. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  2561. HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
  2562. startSpecifier, specifierLen);
  2563. return false;
  2564. }
  2565. }
  2566. // Check if the field with is non-zero.
  2567. const OptionalAmount &Amt = FS.getFieldWidth();
  2568. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  2569. if (Amt.getConstantAmount() == 0) {
  2570. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  2571. Amt.getConstantLength());
  2572. EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
  2573. getLocationOfByte(Amt.getStart()),
  2574. /*IsStringLocation*/true, R,
  2575. FixItHint::CreateRemoval(R));
  2576. }
  2577. }
  2578. if (!FS.consumesDataArgument()) {
  2579. // FIXME: Technically specifying a precision or field width here
  2580. // makes no sense. Worth issuing a warning at some point.
  2581. return true;
  2582. }
  2583. // Consume the argument.
  2584. unsigned argIndex = FS.getArgIndex();
  2585. if (argIndex < NumDataArgs) {
  2586. // The check to see if the argIndex is valid will come later.
  2587. // We set the bit here because we may exit early from this
  2588. // function if we encounter some other error.
  2589. CoveredArgs.set(argIndex);
  2590. }
  2591. // Check the length modifier is valid with the given conversion specifier.
  2592. if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
  2593. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2594. diag::warn_format_nonsensical_length);
  2595. else if (!FS.hasStandardLengthModifier())
  2596. HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
  2597. else if (!FS.hasStandardLengthConversionCombination())
  2598. HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
  2599. diag::warn_format_non_standard_conversion_spec);
  2600. if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
  2601. HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
  2602. // The remaining checks depend on the data arguments.
  2603. if (HasVAListArg)
  2604. return true;
  2605. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  2606. return false;
  2607. // Check that the argument type matches the format specifier.
  2608. const Expr *Ex = getDataArg(argIndex);
  2609. if (!Ex)
  2610. return true;
  2611. const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
  2612. if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
  2613. ScanfSpecifier fixedFS = FS;
  2614. bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
  2615. S.Context);
  2616. if (success) {
  2617. // Get the fix string from the fixed format specifier.
  2618. SmallString<128> buf;
  2619. llvm::raw_svector_ostream os(buf);
  2620. fixedFS.toString(os);
  2621. EmitFormatDiagnostic(
  2622. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2623. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  2624. << Ex->getSourceRange(),
  2625. Ex->getLocStart(),
  2626. /*IsStringLocation*/false,
  2627. getSpecifierRange(startSpecifier, specifierLen),
  2628. FixItHint::CreateReplacement(
  2629. getSpecifierRange(startSpecifier, specifierLen),
  2630. os.str()));
  2631. } else {
  2632. EmitFormatDiagnostic(
  2633. S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
  2634. << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
  2635. << Ex->getSourceRange(),
  2636. Ex->getLocStart(),
  2637. /*IsStringLocation*/false,
  2638. getSpecifierRange(startSpecifier, specifierLen));
  2639. }
  2640. }
  2641. return true;
  2642. }
  2643. void Sema::CheckFormatString(const StringLiteral *FExpr,
  2644. const Expr *OrigFormatExpr,
  2645. Expr **Args, unsigned NumArgs,
  2646. bool HasVAListArg, unsigned format_idx,
  2647. unsigned firstDataArg, FormatStringType Type,
  2648. bool inFunctionCall, VariadicCallType CallType) {
  2649. // CHECK: is the format string a wide literal?
  2650. if (!FExpr->isAscii() && !FExpr->isUTF8()) {
  2651. CheckFormatHandler::EmitFormatDiagnostic(
  2652. *this, inFunctionCall, Args[format_idx],
  2653. PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
  2654. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2655. return;
  2656. }
  2657. // Str - The format string. NOTE: this is NOT null-terminated!
  2658. StringRef StrRef = FExpr->getString();
  2659. const char *Str = StrRef.data();
  2660. unsigned StrLen = StrRef.size();
  2661. const unsigned numDataArgs = NumArgs - firstDataArg;
  2662. // CHECK: empty format string?
  2663. if (StrLen == 0 && numDataArgs > 0) {
  2664. CheckFormatHandler::EmitFormatDiagnostic(
  2665. *this, inFunctionCall, Args[format_idx],
  2666. PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
  2667. /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
  2668. return;
  2669. }
  2670. if (Type == FST_Printf || Type == FST_NSString) {
  2671. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  2672. numDataArgs, (Type == FST_NSString),
  2673. Str, HasVAListArg, Args, NumArgs, format_idx,
  2674. inFunctionCall, CallType);
  2675. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
  2676. getLangOpts(),
  2677. Context.getTargetInfo()))
  2678. H.DoneProcessing();
  2679. } else if (Type == FST_Scanf) {
  2680. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
  2681. Str, HasVAListArg, Args, NumArgs, format_idx,
  2682. inFunctionCall, CallType);
  2683. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
  2684. getLangOpts(),
  2685. Context.getTargetInfo()))
  2686. H.DoneProcessing();
  2687. } // TODO: handle other formats
  2688. }
  2689. //===--- CHECK: Standard memory functions ---------------------------------===//
  2690. /// \brief Determine whether the given type is a dynamic class type (e.g.,
  2691. /// whether it has a vtable).
  2692. static bool isDynamicClassType(QualType T) {
  2693. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  2694. if (CXXRecordDecl *Definition = Record->getDefinition())
  2695. if (Definition->isDynamicClass())
  2696. return true;
  2697. return false;
  2698. }
  2699. /// \brief If E is a sizeof expression, returns its argument expression,
  2700. /// otherwise returns NULL.
  2701. static const Expr *getSizeOfExprArg(const Expr* E) {
  2702. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2703. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2704. if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
  2705. return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
  2706. return 0;
  2707. }
  2708. /// \brief If E is a sizeof expression, returns its argument type.
  2709. static QualType getSizeOfArgType(const Expr* E) {
  2710. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  2711. dyn_cast<UnaryExprOrTypeTraitExpr>(E))
  2712. if (SizeOf->getKind() == clang::UETT_SizeOf)
  2713. return SizeOf->getTypeOfArgument();
  2714. return QualType();
  2715. }
  2716. /// \brief Check for dangerous or invalid arguments to memset().
  2717. ///
  2718. /// This issues warnings on known problematic, dangerous or unspecified
  2719. /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
  2720. /// function calls.
  2721. ///
  2722. /// \param Call The call expression to diagnose.
  2723. void Sema::CheckMemaccessArguments(const CallExpr *Call,
  2724. unsigned BId,
  2725. IdentifierInfo *FnName) {
  2726. assert(BId != 0);
  2727. // It is possible to have a non-standard definition of memset. Validate
  2728. // we have enough arguments, and if not, abort further checking.
  2729. unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
  2730. if (Call->getNumArgs() < ExpectedNumArgs)
  2731. return;
  2732. unsigned LastArg = (BId == Builtin::BImemset ||
  2733. BId == Builtin::BIstrndup ? 1 : 2);
  2734. unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
  2735. const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
  2736. // We have special checking when the length is a sizeof expression.
  2737. QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
  2738. const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
  2739. llvm::FoldingSetNodeID SizeOfArgID;
  2740. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  2741. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  2742. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  2743. QualType DestTy = Dest->getType();
  2744. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  2745. QualType PointeeTy = DestPtrTy->getPointeeType();
  2746. // Never warn about void type pointers. This can be used to suppress
  2747. // false positives.
  2748. if (PointeeTy->isVoidType())
  2749. continue;
  2750. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
  2751. // actually comparing the expressions for equality. Because computing the
  2752. // expression IDs can be expensive, we only do this if the diagnostic is
  2753. // enabled.
  2754. if (SizeOfArg &&
  2755. Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
  2756. SizeOfArg->getExprLoc())) {
  2757. // We only compute IDs for expressions if the warning is enabled, and
  2758. // cache the sizeof arg's ID.
  2759. if (SizeOfArgID == llvm::FoldingSetNodeID())
  2760. SizeOfArg->Profile(SizeOfArgID, Context, true);
  2761. llvm::FoldingSetNodeID DestID;
  2762. Dest->Profile(DestID, Context, true);
  2763. if (DestID == SizeOfArgID) {
  2764. // TODO: For strncpy() and friends, this could suggest sizeof(dst)
  2765. // over sizeof(src) as well.
  2766. unsigned ActionIdx = 0; // Default is to suggest dereferencing.
  2767. StringRef ReadableName = FnName->getName();
  2768. if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
  2769. if (UnaryOp->getOpcode() == UO_AddrOf)
  2770. ActionIdx = 1; // If its an address-of operator, just remove it.
  2771. if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
  2772. ActionIdx = 2; // If the pointee's size is sizeof(char),
  2773. // suggest an explicit length.
  2774. // If the function is defined as a builtin macro, do not show macro
  2775. // expansion.
  2776. SourceLocation SL = SizeOfArg->getExprLoc();
  2777. SourceRange DSR = Dest->getSourceRange();
  2778. SourceRange SSR = SizeOfArg->getSourceRange();
  2779. SourceManager &SM = PP.getSourceManager();
  2780. if (SM.isMacroArgExpansion(SL)) {
  2781. ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
  2782. SL = SM.getSpellingLoc(SL);
  2783. DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
  2784. SM.getSpellingLoc(DSR.getEnd()));
  2785. SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
  2786. SM.getSpellingLoc(SSR.getEnd()));
  2787. }
  2788. DiagRuntimeBehavior(SL, SizeOfArg,
  2789. PDiag(diag::warn_sizeof_pointer_expr_memaccess)
  2790. << ReadableName
  2791. << PointeeTy
  2792. << DestTy
  2793. << DSR
  2794. << SSR);
  2795. DiagRuntimeBehavior(SL, SizeOfArg,
  2796. PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
  2797. << ActionIdx
  2798. << SSR);
  2799. break;
  2800. }
  2801. }
  2802. // Also check for cases where the sizeof argument is the exact same
  2803. // type as the memory argument, and where it points to a user-defined
  2804. // record type.
  2805. if (SizeOfArgTy != QualType()) {
  2806. if (PointeeTy->isRecordType() &&
  2807. Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
  2808. DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
  2809. PDiag(diag::warn_sizeof_pointer_type_memaccess)
  2810. << FnName << SizeOfArgTy << ArgIdx
  2811. << PointeeTy << Dest->getSourceRange()
  2812. << LenExpr->getSourceRange());
  2813. break;
  2814. }
  2815. }
  2816. // Always complain about dynamic classes.
  2817. if (isDynamicClassType(PointeeTy)) {
  2818. unsigned OperationType = 0;
  2819. // "overwritten" if we're warning about the destination for any call
  2820. // but memcmp; otherwise a verb appropriate to the call.
  2821. if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
  2822. if (BId == Builtin::BImemcpy)
  2823. OperationType = 1;
  2824. else if(BId == Builtin::BImemmove)
  2825. OperationType = 2;
  2826. else if (BId == Builtin::BImemcmp)
  2827. OperationType = 3;
  2828. }
  2829. DiagRuntimeBehavior(
  2830. Dest->getExprLoc(), Dest,
  2831. PDiag(diag::warn_dyn_class_memaccess)
  2832. << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
  2833. << FnName << PointeeTy
  2834. << OperationType
  2835. << Call->getCallee()->getSourceRange());
  2836. } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  2837. BId != Builtin::BImemset)
  2838. DiagRuntimeBehavior(
  2839. Dest->getExprLoc(), Dest,
  2840. PDiag(diag::warn_arc_object_memaccess)
  2841. << ArgIdx << FnName << PointeeTy
  2842. << Call->getCallee()->getSourceRange());
  2843. else
  2844. continue;
  2845. DiagRuntimeBehavior(
  2846. Dest->getExprLoc(), Dest,
  2847. PDiag(diag::note_bad_memaccess_silence)
  2848. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  2849. break;
  2850. }
  2851. }
  2852. }
  2853. // A little helper routine: ignore addition and subtraction of integer literals.
  2854. // This intentionally does not ignore all integer constant expressions because
  2855. // we don't want to remove sizeof().
  2856. static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
  2857. Ex = Ex->IgnoreParenCasts();
  2858. for (;;) {
  2859. const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
  2860. if (!BO || !BO->isAdditiveOp())
  2861. break;
  2862. const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
  2863. const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
  2864. if (isa<IntegerLiteral>(RHS))
  2865. Ex = LHS;
  2866. else if (isa<IntegerLiteral>(LHS))
  2867. Ex = RHS;
  2868. else
  2869. break;
  2870. }
  2871. return Ex;
  2872. }
  2873. static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
  2874. ASTContext &Context) {
  2875. // Only handle constant-sized or VLAs, but not flexible members.
  2876. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
  2877. // Only issue the FIXIT for arrays of size > 1.
  2878. if (CAT->getSize().getSExtValue() <= 1)
  2879. return false;
  2880. } else if (!Ty->isVariableArrayType()) {
  2881. return false;
  2882. }
  2883. return true;
  2884. }
  2885. // Warn if the user has made the 'size' argument to strlcpy or strlcat
  2886. // be the size of the source, instead of the destination.
  2887. void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
  2888. IdentifierInfo *FnName) {
  2889. // Don't crash if the user has the wrong number of arguments
  2890. if (Call->getNumArgs() != 3)
  2891. return;
  2892. const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
  2893. const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
  2894. const Expr *CompareWithSrc = NULL;
  2895. // Look for 'strlcpy(dst, x, sizeof(x))'
  2896. if (const Expr *Ex = getSizeOfExprArg(SizeArg))
  2897. CompareWithSrc = Ex;
  2898. else {
  2899. // Look for 'strlcpy(dst, x, strlen(x))'
  2900. if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
  2901. if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
  2902. && SizeCall->getNumArgs() == 1)
  2903. CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
  2904. }
  2905. }
  2906. if (!CompareWithSrc)
  2907. return;
  2908. // Determine if the argument to sizeof/strlen is equal to the source
  2909. // argument. In principle there's all kinds of things you could do
  2910. // here, for instance creating an == expression and evaluating it with
  2911. // EvaluateAsBooleanCondition, but this uses a more direct technique:
  2912. const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
  2913. if (!SrcArgDRE)
  2914. return;
  2915. const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
  2916. if (!CompareWithSrcDRE ||
  2917. SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
  2918. return;
  2919. const Expr *OriginalSizeArg = Call->getArg(2);
  2920. Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
  2921. << OriginalSizeArg->getSourceRange() << FnName;
  2922. // Output a FIXIT hint if the destination is an array (rather than a
  2923. // pointer to an array). This could be enhanced to handle some
  2924. // pointers if we know the actual size, like if DstArg is 'array+2'
  2925. // we could say 'sizeof(array)-2'.
  2926. const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
  2927. if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
  2928. return;
  2929. SmallString<128> sizeString;
  2930. llvm::raw_svector_ostream OS(sizeString);
  2931. OS << "sizeof(";
  2932. DstArg->printPretty(OS, 0, getPrintingPolicy());
  2933. OS << ")";
  2934. Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
  2935. << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
  2936. OS.str());
  2937. }
  2938. /// Check if two expressions refer to the same declaration.
  2939. static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
  2940. if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
  2941. if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
  2942. return D1->getDecl() == D2->getDecl();
  2943. return false;
  2944. }
  2945. static const Expr *getStrlenExprArg(const Expr *E) {
  2946. if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
  2947. const FunctionDecl *FD = CE->getDirectCallee();
  2948. if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
  2949. return 0;
  2950. return CE->getArg(0)->IgnoreParenCasts();
  2951. }
  2952. return 0;
  2953. }
  2954. // Warn on anti-patterns as the 'size' argument to strncat.
  2955. // The correct size argument should look like following:
  2956. // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
  2957. void Sema::CheckStrncatArguments(const CallExpr *CE,
  2958. IdentifierInfo *FnName) {
  2959. // Don't crash if the user has the wrong number of arguments.
  2960. if (CE->getNumArgs() < 3)
  2961. return;
  2962. const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
  2963. const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
  2964. const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
  2965. // Identify common expressions, which are wrongly used as the size argument
  2966. // to strncat and may lead to buffer overflows.
  2967. unsigned PatternType = 0;
  2968. if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
  2969. // - sizeof(dst)
  2970. if (referToTheSameDecl(SizeOfArg, DstArg))
  2971. PatternType = 1;
  2972. // - sizeof(src)
  2973. else if (referToTheSameDecl(SizeOfArg, SrcArg))
  2974. PatternType = 2;
  2975. } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
  2976. if (BE->getOpcode() == BO_Sub) {
  2977. const Expr *L = BE->getLHS()->IgnoreParenCasts();
  2978. const Expr *R = BE->getRHS()->IgnoreParenCasts();
  2979. // - sizeof(dst) - strlen(dst)
  2980. if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
  2981. referToTheSameDecl(DstArg, getStrlenExprArg(R)))
  2982. PatternType = 1;
  2983. // - sizeof(src) - (anything)
  2984. else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
  2985. PatternType = 2;
  2986. }
  2987. }
  2988. if (PatternType == 0)
  2989. return;
  2990. // Generate the diagnostic.
  2991. SourceLocation SL = LenArg->getLocStart();
  2992. SourceRange SR = LenArg->getSourceRange();
  2993. SourceManager &SM = PP.getSourceManager();
  2994. // If the function is defined as a builtin macro, do not show macro expansion.
  2995. if (SM.isMacroArgExpansion(SL)) {
  2996. SL = SM.getSpellingLoc(SL);
  2997. SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
  2998. SM.getSpellingLoc(SR.getEnd()));
  2999. }
  3000. // Check if the destination is an array (rather than a pointer to an array).
  3001. QualType DstTy = DstArg->getType();
  3002. bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
  3003. Context);
  3004. if (!isKnownSizeArray) {
  3005. if (PatternType == 1)
  3006. Diag(SL, diag::warn_strncat_wrong_size) << SR;
  3007. else
  3008. Diag(SL, diag::warn_strncat_src_size) << SR;
  3009. return;
  3010. }
  3011. if (PatternType == 1)
  3012. Diag(SL, diag::warn_strncat_large_size) << SR;
  3013. else
  3014. Diag(SL, diag::warn_strncat_src_size) << SR;
  3015. SmallString<128> sizeString;
  3016. llvm::raw_svector_ostream OS(sizeString);
  3017. OS << "sizeof(";
  3018. DstArg->printPretty(OS, 0, getPrintingPolicy());
  3019. OS << ") - ";
  3020. OS << "strlen(";
  3021. DstArg->printPretty(OS, 0, getPrintingPolicy());
  3022. OS << ") - 1";
  3023. Diag(SL, diag::note_strncat_wrong_size)
  3024. << FixItHint::CreateReplacement(SR, OS.str());
  3025. }
  3026. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  3027. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3028. Decl *ParentDecl);
  3029. static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3030. Decl *ParentDecl);
  3031. /// CheckReturnStackAddr - Check if a return statement returns the address
  3032. /// of a stack variable.
  3033. void
  3034. Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
  3035. SourceLocation ReturnLoc) {
  3036. Expr *stackE = 0;
  3037. SmallVector<DeclRefExpr *, 8> refVars;
  3038. // Perform checking for returned stack addresses, local blocks,
  3039. // label addresses or references to temporaries.
  3040. if (lhsType->isPointerType() ||
  3041. (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  3042. stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
  3043. } else if (lhsType->isReferenceType()) {
  3044. stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
  3045. }
  3046. if (stackE == 0)
  3047. return; // Nothing suspicious was found.
  3048. SourceLocation diagLoc;
  3049. SourceRange diagRange;
  3050. if (refVars.empty()) {
  3051. diagLoc = stackE->getLocStart();
  3052. diagRange = stackE->getSourceRange();
  3053. } else {
  3054. // We followed through a reference variable. 'stackE' contains the
  3055. // problematic expression but we will warn at the return statement pointing
  3056. // at the reference variable. We will later display the "trail" of
  3057. // reference variables using notes.
  3058. diagLoc = refVars[0]->getLocStart();
  3059. diagRange = refVars[0]->getSourceRange();
  3060. }
  3061. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  3062. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  3063. : diag::warn_ret_stack_addr)
  3064. << DR->getDecl()->getDeclName() << diagRange;
  3065. } else if (isa<BlockExpr>(stackE)) { // local block.
  3066. Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  3067. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  3068. Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  3069. } else { // local temporary.
  3070. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  3071. : diag::warn_ret_local_temp_addr)
  3072. << diagRange;
  3073. }
  3074. // Display the "trail" of reference variables that we followed until we
  3075. // found the problematic expression using notes.
  3076. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  3077. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  3078. // If this var binds to another reference var, show the range of the next
  3079. // var, otherwise the var binds to the problematic expression, in which case
  3080. // show the range of the expression.
  3081. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  3082. : stackE->getSourceRange();
  3083. Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  3084. << VD->getDeclName() << range;
  3085. }
  3086. }
  3087. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  3088. /// check if the expression in a return statement evaluates to an address
  3089. /// to a location on the stack, a local block, an address of a label, or a
  3090. /// reference to local temporary. The recursion is used to traverse the
  3091. /// AST of the return expression, with recursion backtracking when we
  3092. /// encounter a subexpression that (1) clearly does not lead to one of the
  3093. /// above problematic expressions (2) is something we cannot determine leads to
  3094. /// a problematic expression based on such local checking.
  3095. ///
  3096. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  3097. /// the expression that they point to. Such variables are added to the
  3098. /// 'refVars' vector so that we know what the reference variable "trail" was.
  3099. ///
  3100. /// EvalAddr processes expressions that are pointers that are used as
  3101. /// references (and not L-values). EvalVal handles all other values.
  3102. /// At the base case of the recursion is a check for the above problematic
  3103. /// expressions.
  3104. ///
  3105. /// This implementation handles:
  3106. ///
  3107. /// * pointer-to-pointer casts
  3108. /// * implicit conversions from array references to pointers
  3109. /// * taking the address of fields
  3110. /// * arbitrary interplay between "&" and "*" operators
  3111. /// * pointer arithmetic from an address of a stack variable
  3112. /// * taking the address of an array element where the array is on the stack
  3113. static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3114. Decl *ParentDecl) {
  3115. if (E->isTypeDependent())
  3116. return NULL;
  3117. // We should only be called for evaluating pointer expressions.
  3118. assert((E->getType()->isAnyPointerType() ||
  3119. E->getType()->isBlockPointerType() ||
  3120. E->getType()->isObjCQualifiedIdType()) &&
  3121. "EvalAddr only works on pointers");
  3122. E = E->IgnoreParens();
  3123. // Our "symbolic interpreter" is just a dispatch off the currently
  3124. // viewed AST node. We then recursively traverse the AST by calling
  3125. // EvalAddr and EvalVal appropriately.
  3126. switch (E->getStmtClass()) {
  3127. case Stmt::DeclRefExprClass: {
  3128. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  3129. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  3130. // If this is a reference variable, follow through to the expression that
  3131. // it points to.
  3132. if (V->hasLocalStorage() &&
  3133. V->getType()->isReferenceType() && V->hasInit()) {
  3134. // Add the reference variable to the "trail".
  3135. refVars.push_back(DR);
  3136. return EvalAddr(V->getInit(), refVars, ParentDecl);
  3137. }
  3138. return NULL;
  3139. }
  3140. case Stmt::UnaryOperatorClass: {
  3141. // The only unary operator that make sense to handle here
  3142. // is AddrOf. All others don't make sense as pointers.
  3143. UnaryOperator *U = cast<UnaryOperator>(E);
  3144. if (U->getOpcode() == UO_AddrOf)
  3145. return EvalVal(U->getSubExpr(), refVars, ParentDecl);
  3146. else
  3147. return NULL;
  3148. }
  3149. case Stmt::BinaryOperatorClass: {
  3150. // Handle pointer arithmetic. All other binary operators are not valid
  3151. // in this context.
  3152. BinaryOperator *B = cast<BinaryOperator>(E);
  3153. BinaryOperatorKind op = B->getOpcode();
  3154. if (op != BO_Add && op != BO_Sub)
  3155. return NULL;
  3156. Expr *Base = B->getLHS();
  3157. // Determine which argument is the real pointer base. It could be
  3158. // the RHS argument instead of the LHS.
  3159. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  3160. assert (Base->getType()->isPointerType());
  3161. return EvalAddr(Base, refVars, ParentDecl);
  3162. }
  3163. // For conditional operators we need to see if either the LHS or RHS are
  3164. // valid DeclRefExpr*s. If one of them is valid, we return it.
  3165. case Stmt::ConditionalOperatorClass: {
  3166. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3167. // Handle the GNU extension for missing LHS.
  3168. if (Expr *lhsExpr = C->getLHS()) {
  3169. // In C++, we can have a throw-expression, which has 'void' type.
  3170. if (!lhsExpr->getType()->isVoidType())
  3171. if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
  3172. return LHS;
  3173. }
  3174. // In C++, we can have a throw-expression, which has 'void' type.
  3175. if (C->getRHS()->getType()->isVoidType())
  3176. return NULL;
  3177. return EvalAddr(C->getRHS(), refVars, ParentDecl);
  3178. }
  3179. case Stmt::BlockExprClass:
  3180. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  3181. return E; // local block.
  3182. return NULL;
  3183. case Stmt::AddrLabelExprClass:
  3184. return E; // address of label.
  3185. case Stmt::ExprWithCleanupsClass:
  3186. return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
  3187. ParentDecl);
  3188. // For casts, we need to handle conversions from arrays to
  3189. // pointer values, and pointer-to-pointer conversions.
  3190. case Stmt::ImplicitCastExprClass:
  3191. case Stmt::CStyleCastExprClass:
  3192. case Stmt::CXXFunctionalCastExprClass:
  3193. case Stmt::ObjCBridgedCastExprClass:
  3194. case Stmt::CXXStaticCastExprClass:
  3195. case Stmt::CXXDynamicCastExprClass:
  3196. case Stmt::CXXConstCastExprClass:
  3197. case Stmt::CXXReinterpretCastExprClass: {
  3198. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  3199. switch (cast<CastExpr>(E)->getCastKind()) {
  3200. case CK_BitCast:
  3201. case CK_LValueToRValue:
  3202. case CK_NoOp:
  3203. case CK_BaseToDerived:
  3204. case CK_DerivedToBase:
  3205. case CK_UncheckedDerivedToBase:
  3206. case CK_Dynamic:
  3207. case CK_CPointerToObjCPointerCast:
  3208. case CK_BlockPointerToObjCPointerCast:
  3209. case CK_AnyPointerToBlockPointerCast:
  3210. return EvalAddr(SubExpr, refVars, ParentDecl);
  3211. case CK_ArrayToPointerDecay:
  3212. return EvalVal(SubExpr, refVars, ParentDecl);
  3213. default:
  3214. return 0;
  3215. }
  3216. }
  3217. case Stmt::MaterializeTemporaryExprClass:
  3218. if (Expr *Result = EvalAddr(
  3219. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  3220. refVars, ParentDecl))
  3221. return Result;
  3222. return E;
  3223. // Everything else: we simply don't reason about them.
  3224. default:
  3225. return NULL;
  3226. }
  3227. }
  3228. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  3229. /// See the comments for EvalAddr for more details.
  3230. static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
  3231. Decl *ParentDecl) {
  3232. do {
  3233. // We should only be called for evaluating non-pointer expressions, or
  3234. // expressions with a pointer type that are not used as references but instead
  3235. // are l-values (e.g., DeclRefExpr with a pointer type).
  3236. // Our "symbolic interpreter" is just a dispatch off the currently
  3237. // viewed AST node. We then recursively traverse the AST by calling
  3238. // EvalAddr and EvalVal appropriately.
  3239. E = E->IgnoreParens();
  3240. switch (E->getStmtClass()) {
  3241. case Stmt::ImplicitCastExprClass: {
  3242. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  3243. if (IE->getValueKind() == VK_LValue) {
  3244. E = IE->getSubExpr();
  3245. continue;
  3246. }
  3247. return NULL;
  3248. }
  3249. case Stmt::ExprWithCleanupsClass:
  3250. return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
  3251. case Stmt::DeclRefExprClass: {
  3252. // When we hit a DeclRefExpr we are looking at code that refers to a
  3253. // variable's name. If it's not a reference variable we check if it has
  3254. // local storage within the function, and if so, return the expression.
  3255. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  3256. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
  3257. // Check if it refers to itself, e.g. "int& i = i;".
  3258. if (V == ParentDecl)
  3259. return DR;
  3260. if (V->hasLocalStorage()) {
  3261. if (!V->getType()->isReferenceType())
  3262. return DR;
  3263. // Reference variable, follow through to the expression that
  3264. // it points to.
  3265. if (V->hasInit()) {
  3266. // Add the reference variable to the "trail".
  3267. refVars.push_back(DR);
  3268. return EvalVal(V->getInit(), refVars, V);
  3269. }
  3270. }
  3271. }
  3272. return NULL;
  3273. }
  3274. case Stmt::UnaryOperatorClass: {
  3275. // The only unary operator that make sense to handle here
  3276. // is Deref. All others don't resolve to a "name." This includes
  3277. // handling all sorts of rvalues passed to a unary operator.
  3278. UnaryOperator *U = cast<UnaryOperator>(E);
  3279. if (U->getOpcode() == UO_Deref)
  3280. return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
  3281. return NULL;
  3282. }
  3283. case Stmt::ArraySubscriptExprClass: {
  3284. // Array subscripts are potential references to data on the stack. We
  3285. // retrieve the DeclRefExpr* for the array variable if it indeed
  3286. // has local storage.
  3287. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
  3288. }
  3289. case Stmt::ConditionalOperatorClass: {
  3290. // For conditional operators we need to see if either the LHS or RHS are
  3291. // non-NULL Expr's. If one is non-NULL, we return it.
  3292. ConditionalOperator *C = cast<ConditionalOperator>(E);
  3293. // Handle the GNU extension for missing LHS.
  3294. if (Expr *lhsExpr = C->getLHS())
  3295. if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
  3296. return LHS;
  3297. return EvalVal(C->getRHS(), refVars, ParentDecl);
  3298. }
  3299. // Accesses to members are potential references to data on the stack.
  3300. case Stmt::MemberExprClass: {
  3301. MemberExpr *M = cast<MemberExpr>(E);
  3302. // Check for indirect access. We only want direct field accesses.
  3303. if (M->isArrow())
  3304. return NULL;
  3305. // Check whether the member type is itself a reference, in which case
  3306. // we're not going to refer to the member, but to what the member refers to.
  3307. if (M->getMemberDecl()->getType()->isReferenceType())
  3308. return NULL;
  3309. return EvalVal(M->getBase(), refVars, ParentDecl);
  3310. }
  3311. case Stmt::MaterializeTemporaryExprClass:
  3312. if (Expr *Result = EvalVal(
  3313. cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
  3314. refVars, ParentDecl))
  3315. return Result;
  3316. return E;
  3317. default:
  3318. // Check that we don't return or take the address of a reference to a
  3319. // temporary. This is only useful in C++.
  3320. if (!E->isTypeDependent() && E->isRValue())
  3321. return E;
  3322. // Everything else: we simply don't reason about them.
  3323. return NULL;
  3324. }
  3325. } while (true);
  3326. }
  3327. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  3328. /// Check for comparisons of floating point operands using != and ==.
  3329. /// Issue a warning if these are no self-comparisons, as they are not likely
  3330. /// to do what the programmer intended.
  3331. void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
  3332. Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
  3333. Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
  3334. // Special case: check for x == x (which is OK).
  3335. // Do not emit warnings for such cases.
  3336. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  3337. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  3338. if (DRL->getDecl() == DRR->getDecl())
  3339. return;
  3340. // Special case: check for comparisons against literals that can be exactly
  3341. // represented by APFloat. In such cases, do not emit a warning. This
  3342. // is a heuristic: often comparison against such literals are used to
  3343. // detect if a value in a variable has not changed. This clearly can
  3344. // lead to false negatives.
  3345. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  3346. if (FLL->isExact())
  3347. return;
  3348. } else
  3349. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
  3350. if (FLR->isExact())
  3351. return;
  3352. // Check for comparisons with builtin types.
  3353. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  3354. if (CL->isBuiltinCall())
  3355. return;
  3356. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  3357. if (CR->isBuiltinCall())
  3358. return;
  3359. // Emit the diagnostic.
  3360. Diag(Loc, diag::warn_floatingpoint_eq)
  3361. << LHS->getSourceRange() << RHS->getSourceRange();
  3362. }
  3363. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  3364. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  3365. namespace {
  3366. /// Structure recording the 'active' range of an integer-valued
  3367. /// expression.
  3368. struct IntRange {
  3369. /// The number of bits active in the int.
  3370. unsigned Width;
  3371. /// True if the int is known not to have negative values.
  3372. bool NonNegative;
  3373. IntRange(unsigned Width, bool NonNegative)
  3374. : Width(Width), NonNegative(NonNegative)
  3375. {}
  3376. /// Returns the range of the bool type.
  3377. static IntRange forBoolType() {
  3378. return IntRange(1, true);
  3379. }
  3380. /// Returns the range of an opaque value of the given integral type.
  3381. static IntRange forValueOfType(ASTContext &C, QualType T) {
  3382. return forValueOfCanonicalType(C,
  3383. T->getCanonicalTypeInternal().getTypePtr());
  3384. }
  3385. /// Returns the range of an opaque value of a canonical integral type.
  3386. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  3387. assert(T->isCanonicalUnqualified());
  3388. if (const VectorType *VT = dyn_cast<VectorType>(T))
  3389. T = VT->getElementType().getTypePtr();
  3390. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  3391. T = CT->getElementType().getTypePtr();
  3392. // For enum types, use the known bit width of the enumerators.
  3393. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  3394. EnumDecl *Enum = ET->getDecl();
  3395. if (!Enum->isCompleteDefinition())
  3396. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  3397. unsigned NumPositive = Enum->getNumPositiveBits();
  3398. unsigned NumNegative = Enum->getNumNegativeBits();
  3399. return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
  3400. }
  3401. const BuiltinType *BT = cast<BuiltinType>(T);
  3402. assert(BT->isInteger());
  3403. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  3404. }
  3405. /// Returns the "target" range of a canonical integral type, i.e.
  3406. /// the range of values expressible in the type.
  3407. ///
  3408. /// This matches forValueOfCanonicalType except that enums have the
  3409. /// full range of their type, not the range of their enumerators.
  3410. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  3411. assert(T->isCanonicalUnqualified());
  3412. if (const VectorType *VT = dyn_cast<VectorType>(T))
  3413. T = VT->getElementType().getTypePtr();
  3414. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  3415. T = CT->getElementType().getTypePtr();
  3416. if (const EnumType *ET = dyn_cast<EnumType>(T))
  3417. T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
  3418. const BuiltinType *BT = cast<BuiltinType>(T);
  3419. assert(BT->isInteger());
  3420. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  3421. }
  3422. /// Returns the supremum of two ranges: i.e. their conservative merge.
  3423. static IntRange join(IntRange L, IntRange R) {
  3424. return IntRange(std::max(L.Width, R.Width),
  3425. L.NonNegative && R.NonNegative);
  3426. }
  3427. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  3428. static IntRange meet(IntRange L, IntRange R) {
  3429. return IntRange(std::min(L.Width, R.Width),
  3430. L.NonNegative || R.NonNegative);
  3431. }
  3432. };
  3433. static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
  3434. unsigned MaxWidth) {
  3435. if (value.isSigned() && value.isNegative())
  3436. return IntRange(value.getMinSignedBits(), false);
  3437. if (value.getBitWidth() > MaxWidth)
  3438. value = value.trunc(MaxWidth);
  3439. // isNonNegative() just checks the sign bit without considering
  3440. // signedness.
  3441. return IntRange(value.getActiveBits(), true);
  3442. }
  3443. static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  3444. unsigned MaxWidth) {
  3445. if (result.isInt())
  3446. return GetValueRange(C, result.getInt(), MaxWidth);
  3447. if (result.isVector()) {
  3448. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  3449. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  3450. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  3451. R = IntRange::join(R, El);
  3452. }
  3453. return R;
  3454. }
  3455. if (result.isComplexInt()) {
  3456. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  3457. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  3458. return IntRange::join(R, I);
  3459. }
  3460. // This can happen with lossless casts to intptr_t of "based" lvalues.
  3461. // Assume it might use arbitrary bits.
  3462. // FIXME: The only reason we need to pass the type in here is to get
  3463. // the sign right on this one case. It would be nice if APValue
  3464. // preserved this.
  3465. assert(result.isLValue() || result.isAddrLabelDiff());
  3466. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  3467. }
  3468. /// Pseudo-evaluate the given integer expression, estimating the
  3469. /// range of values it might take.
  3470. ///
  3471. /// \param MaxWidth - the width to which the value will be truncated
  3472. static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  3473. E = E->IgnoreParens();
  3474. // Try a full evaluation first.
  3475. Expr::EvalResult result;
  3476. if (E->EvaluateAsRValue(result, C))
  3477. return GetValueRange(C, result.Val, E->getType(), MaxWidth);
  3478. // I think we only want to look through implicit casts here; if the
  3479. // user has an explicit widening cast, we should treat the value as
  3480. // being of the new, wider type.
  3481. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  3482. if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
  3483. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  3484. IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
  3485. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  3486. // Assume that non-integer casts can span the full range of the type.
  3487. if (!isIntegerCast)
  3488. return OutputTypeRange;
  3489. IntRange SubRange
  3490. = GetExprRange(C, CE->getSubExpr(),
  3491. std::min(MaxWidth, OutputTypeRange.Width));
  3492. // Bail out if the subexpr's range is as wide as the cast type.
  3493. if (SubRange.Width >= OutputTypeRange.Width)
  3494. return OutputTypeRange;
  3495. // Otherwise, we take the smaller width, and we're non-negative if
  3496. // either the output type or the subexpr is.
  3497. return IntRange(SubRange.Width,
  3498. SubRange.NonNegative || OutputTypeRange.NonNegative);
  3499. }
  3500. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  3501. // If we can fold the condition, just take that operand.
  3502. bool CondResult;
  3503. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  3504. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  3505. : CO->getFalseExpr(),
  3506. MaxWidth);
  3507. // Otherwise, conservatively merge.
  3508. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  3509. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  3510. return IntRange::join(L, R);
  3511. }
  3512. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  3513. switch (BO->getOpcode()) {
  3514. // Boolean-valued operations are single-bit and positive.
  3515. case BO_LAnd:
  3516. case BO_LOr:
  3517. case BO_LT:
  3518. case BO_GT:
  3519. case BO_LE:
  3520. case BO_GE:
  3521. case BO_EQ:
  3522. case BO_NE:
  3523. return IntRange::forBoolType();
  3524. // The type of the assignments is the type of the LHS, so the RHS
  3525. // is not necessarily the same type.
  3526. case BO_MulAssign:
  3527. case BO_DivAssign:
  3528. case BO_RemAssign:
  3529. case BO_AddAssign:
  3530. case BO_SubAssign:
  3531. case BO_XorAssign:
  3532. case BO_OrAssign:
  3533. // TODO: bitfields?
  3534. return IntRange::forValueOfType(C, E->getType());
  3535. // Simple assignments just pass through the RHS, which will have
  3536. // been coerced to the LHS type.
  3537. case BO_Assign:
  3538. // TODO: bitfields?
  3539. return GetExprRange(C, BO->getRHS(), MaxWidth);
  3540. // Operations with opaque sources are black-listed.
  3541. case BO_PtrMemD:
  3542. case BO_PtrMemI:
  3543. return IntRange::forValueOfType(C, E->getType());
  3544. // Bitwise-and uses the *infinum* of the two source ranges.
  3545. case BO_And:
  3546. case BO_AndAssign:
  3547. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  3548. GetExprRange(C, BO->getRHS(), MaxWidth));
  3549. // Left shift gets black-listed based on a judgement call.
  3550. case BO_Shl:
  3551. // ...except that we want to treat '1 << (blah)' as logically
  3552. // positive. It's an important idiom.
  3553. if (IntegerLiteral *I
  3554. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  3555. if (I->getValue() == 1) {
  3556. IntRange R = IntRange::forValueOfType(C, E->getType());
  3557. return IntRange(R.Width, /*NonNegative*/ true);
  3558. }
  3559. }
  3560. // fallthrough
  3561. case BO_ShlAssign:
  3562. return IntRange::forValueOfType(C, E->getType());
  3563. // Right shift by a constant can narrow its left argument.
  3564. case BO_Shr:
  3565. case BO_ShrAssign: {
  3566. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  3567. // If the shift amount is a positive constant, drop the width by
  3568. // that much.
  3569. llvm::APSInt shift;
  3570. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  3571. shift.isNonNegative()) {
  3572. unsigned zext = shift.getZExtValue();
  3573. if (zext >= L.Width)
  3574. L.Width = (L.NonNegative ? 0 : 1);
  3575. else
  3576. L.Width -= zext;
  3577. }
  3578. return L;
  3579. }
  3580. // Comma acts as its right operand.
  3581. case BO_Comma:
  3582. return GetExprRange(C, BO->getRHS(), MaxWidth);
  3583. // Black-list pointer subtractions.
  3584. case BO_Sub:
  3585. if (BO->getLHS()->getType()->isPointerType())
  3586. return IntRange::forValueOfType(C, E->getType());
  3587. break;
  3588. // The width of a division result is mostly determined by the size
  3589. // of the LHS.
  3590. case BO_Div: {
  3591. // Don't 'pre-truncate' the operands.
  3592. unsigned opWidth = C.getIntWidth(E->getType());
  3593. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  3594. // If the divisor is constant, use that.
  3595. llvm::APSInt divisor;
  3596. if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
  3597. unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
  3598. if (log2 >= L.Width)
  3599. L.Width = (L.NonNegative ? 0 : 1);
  3600. else
  3601. L.Width = std::min(L.Width - log2, MaxWidth);
  3602. return L;
  3603. }
  3604. // Otherwise, just use the LHS's width.
  3605. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  3606. return IntRange(L.Width, L.NonNegative && R.NonNegative);
  3607. }
  3608. // The result of a remainder can't be larger than the result of
  3609. // either side.
  3610. case BO_Rem: {
  3611. // Don't 'pre-truncate' the operands.
  3612. unsigned opWidth = C.getIntWidth(E->getType());
  3613. IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
  3614. IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
  3615. IntRange meet = IntRange::meet(L, R);
  3616. meet.Width = std::min(meet.Width, MaxWidth);
  3617. return meet;
  3618. }
  3619. // The default behavior is okay for these.
  3620. case BO_Mul:
  3621. case BO_Add:
  3622. case BO_Xor:
  3623. case BO_Or:
  3624. break;
  3625. }
  3626. // The default case is to treat the operation as if it were closed
  3627. // on the narrowest type that encompasses both operands.
  3628. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  3629. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  3630. return IntRange::join(L, R);
  3631. }
  3632. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  3633. switch (UO->getOpcode()) {
  3634. // Boolean-valued operations are white-listed.
  3635. case UO_LNot:
  3636. return IntRange::forBoolType();
  3637. // Operations with opaque sources are black-listed.
  3638. case UO_Deref:
  3639. case UO_AddrOf: // should be impossible
  3640. return IntRange::forValueOfType(C, E->getType());
  3641. default:
  3642. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  3643. }
  3644. }
  3645. if (dyn_cast<OffsetOfExpr>(E)) {
  3646. IntRange::forValueOfType(C, E->getType());
  3647. }
  3648. if (FieldDecl *BitField = E->getBitField())
  3649. return IntRange(BitField->getBitWidthValue(C),
  3650. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  3651. return IntRange::forValueOfType(C, E->getType());
  3652. }
  3653. static IntRange GetExprRange(ASTContext &C, Expr *E) {
  3654. return GetExprRange(C, E, C.getIntWidth(E->getType()));
  3655. }
  3656. /// Checks whether the given value, which currently has the given
  3657. /// source semantics, has the same value when coerced through the
  3658. /// target semantics.
  3659. static bool IsSameFloatAfterCast(const llvm::APFloat &value,
  3660. const llvm::fltSemantics &Src,
  3661. const llvm::fltSemantics &Tgt) {
  3662. llvm::APFloat truncated = value;
  3663. bool ignored;
  3664. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  3665. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  3666. return truncated.bitwiseIsEqual(value);
  3667. }
  3668. /// Checks whether the given value, which currently has the given
  3669. /// source semantics, has the same value when coerced through the
  3670. /// target semantics.
  3671. ///
  3672. /// The value might be a vector of floats (or a complex number).
  3673. static bool IsSameFloatAfterCast(const APValue &value,
  3674. const llvm::fltSemantics &Src,
  3675. const llvm::fltSemantics &Tgt) {
  3676. if (value.isFloat())
  3677. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  3678. if (value.isVector()) {
  3679. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  3680. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  3681. return false;
  3682. return true;
  3683. }
  3684. assert(value.isComplexFloat());
  3685. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  3686. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  3687. }
  3688. static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  3689. static bool IsZero(Sema &S, Expr *E) {
  3690. // Suppress cases where we are comparing against an enum constant.
  3691. if (const DeclRefExpr *DR =
  3692. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  3693. if (isa<EnumConstantDecl>(DR->getDecl()))
  3694. return false;
  3695. // Suppress cases where the '0' value is expanded from a macro.
  3696. if (E->getLocStart().isMacroID())
  3697. return false;
  3698. llvm::APSInt Value;
  3699. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  3700. }
  3701. static bool HasEnumType(Expr *E) {
  3702. // Strip off implicit integral promotions.
  3703. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  3704. if (ICE->getCastKind() != CK_IntegralCast &&
  3705. ICE->getCastKind() != CK_NoOp)
  3706. break;
  3707. E = ICE->getSubExpr();
  3708. }
  3709. return E->getType()->isEnumeralType();
  3710. }
  3711. static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  3712. BinaryOperatorKind op = E->getOpcode();
  3713. if (E->isValueDependent())
  3714. return;
  3715. if (op == BO_LT && IsZero(S, E->getRHS())) {
  3716. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3717. << "< 0" << "false" << HasEnumType(E->getLHS())
  3718. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3719. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  3720. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  3721. << ">= 0" << "true" << HasEnumType(E->getLHS())
  3722. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3723. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  3724. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3725. << "0 >" << "false" << HasEnumType(E->getRHS())
  3726. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3727. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  3728. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  3729. << "0 <=" << "true" << HasEnumType(E->getRHS())
  3730. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  3731. }
  3732. }
  3733. /// Analyze the operands of the given comparison. Implements the
  3734. /// fallback case from AnalyzeComparison.
  3735. static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  3736. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3737. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3738. }
  3739. /// \brief Implements -Wsign-compare.
  3740. ///
  3741. /// \param E the binary operator to check for warnings
  3742. static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  3743. // The type the comparison is being performed in.
  3744. QualType T = E->getLHS()->getType();
  3745. assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
  3746. && "comparison with mismatched types");
  3747. // We don't do anything special if this isn't an unsigned integral
  3748. // comparison: we're only interested in integral comparisons, and
  3749. // signed comparisons only happen in cases we don't care to warn about.
  3750. //
  3751. // We also don't care about value-dependent expressions or expressions
  3752. // whose result is a constant.
  3753. if (!T->hasUnsignedIntegerRepresentation()
  3754. || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
  3755. return AnalyzeImpConvsInComparison(S, E);
  3756. Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
  3757. Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
  3758. // Check to see if one of the (unmodified) operands is of different
  3759. // signedness.
  3760. Expr *signedOperand, *unsignedOperand;
  3761. if (LHS->getType()->hasSignedIntegerRepresentation()) {
  3762. assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
  3763. "unsigned comparison between two signed integer expressions?");
  3764. signedOperand = LHS;
  3765. unsignedOperand = RHS;
  3766. } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
  3767. signedOperand = RHS;
  3768. unsignedOperand = LHS;
  3769. } else {
  3770. CheckTrivialUnsignedComparison(S, E);
  3771. return AnalyzeImpConvsInComparison(S, E);
  3772. }
  3773. // Otherwise, calculate the effective range of the signed operand.
  3774. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  3775. // Go ahead and analyze implicit conversions in the operands. Note
  3776. // that we skip the implicit conversions on both sides.
  3777. AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
  3778. AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
  3779. // If the signed range is non-negative, -Wsign-compare won't fire,
  3780. // but we should still check for comparisons which are always true
  3781. // or false.
  3782. if (signedRange.NonNegative)
  3783. return CheckTrivialUnsignedComparison(S, E);
  3784. // For (in)equality comparisons, if the unsigned operand is a
  3785. // constant which cannot collide with a overflowed signed operand,
  3786. // then reinterpreting the signed operand as unsigned will not
  3787. // change the result of the comparison.
  3788. if (E->isEqualityOp()) {
  3789. unsigned comparisonWidth = S.Context.getIntWidth(T);
  3790. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  3791. // We should never be unable to prove that the unsigned operand is
  3792. // non-negative.
  3793. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  3794. if (unsignedRange.Width < comparisonWidth)
  3795. return;
  3796. }
  3797. S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
  3798. S.PDiag(diag::warn_mixed_sign_comparison)
  3799. << LHS->getType() << RHS->getType()
  3800. << LHS->getSourceRange() << RHS->getSourceRange());
  3801. }
  3802. /// Analyzes an attempt to assign the given value to a bitfield.
  3803. ///
  3804. /// Returns true if there was something fishy about the attempt.
  3805. static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  3806. SourceLocation InitLoc) {
  3807. assert(Bitfield->isBitField());
  3808. if (Bitfield->isInvalidDecl())
  3809. return false;
  3810. // White-list bool bitfields.
  3811. if (Bitfield->getType()->isBooleanType())
  3812. return false;
  3813. // Ignore value- or type-dependent expressions.
  3814. if (Bitfield->getBitWidth()->isValueDependent() ||
  3815. Bitfield->getBitWidth()->isTypeDependent() ||
  3816. Init->isValueDependent() ||
  3817. Init->isTypeDependent())
  3818. return false;
  3819. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  3820. llvm::APSInt Value;
  3821. if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
  3822. return false;
  3823. unsigned OriginalWidth = Value.getBitWidth();
  3824. unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
  3825. if (OriginalWidth <= FieldWidth)
  3826. return false;
  3827. // Compute the value which the bitfield will contain.
  3828. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  3829. TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
  3830. // Check whether the stored value is equal to the original value.
  3831. TruncatedValue = TruncatedValue.extend(OriginalWidth);
  3832. if (llvm::APSInt::isSameValue(Value, TruncatedValue))
  3833. return false;
  3834. // Special-case bitfields of width 1: booleans are naturally 0/1, and
  3835. // therefore don't strictly fit into a signed bitfield of width 1.
  3836. if (FieldWidth == 1 && Value == 1)
  3837. return false;
  3838. std::string PrettyValue = Value.toString(10);
  3839. std::string PrettyTrunc = TruncatedValue.toString(10);
  3840. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  3841. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  3842. << Init->getSourceRange();
  3843. return true;
  3844. }
  3845. /// Analyze the given simple or compound assignment for warning-worthy
  3846. /// operations.
  3847. static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  3848. // Just recurse on the LHS.
  3849. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  3850. // We want to recurse on the RHS as normal unless we're assigning to
  3851. // a bitfield.
  3852. if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
  3853. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  3854. E->getOperatorLoc())) {
  3855. // Recurse, ignoring any implicit conversions on the RHS.
  3856. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  3857. E->getOperatorLoc());
  3858. }
  3859. }
  3860. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  3861. }
  3862. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3863. static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  3864. SourceLocation CContext, unsigned diag,
  3865. bool pruneControlFlow = false) {
  3866. if (pruneControlFlow) {
  3867. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  3868. S.PDiag(diag)
  3869. << SourceType << T << E->getSourceRange()
  3870. << SourceRange(CContext));
  3871. return;
  3872. }
  3873. S.Diag(E->getExprLoc(), diag)
  3874. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  3875. }
  3876. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  3877. static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
  3878. SourceLocation CContext, unsigned diag,
  3879. bool pruneControlFlow = false) {
  3880. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
  3881. }
  3882. /// Diagnose an implicit cast from a literal expression. Does not warn when the
  3883. /// cast wouldn't lose information.
  3884. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  3885. SourceLocation CContext) {
  3886. // Try to convert the literal exactly to an integer. If we can, don't warn.
  3887. bool isExact = false;
  3888. const llvm::APFloat &Value = FL->getValue();
  3889. llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
  3890. T->hasUnsignedIntegerRepresentation());
  3891. if (Value.convertToInteger(IntegerValue,
  3892. llvm::APFloat::rmTowardZero, &isExact)
  3893. == llvm::APFloat::opOK && isExact)
  3894. return;
  3895. SmallString<16> PrettySourceValue;
  3896. Value.toString(PrettySourceValue);
  3897. SmallString<16> PrettyTargetValue;
  3898. if (T->isSpecificBuiltinType(BuiltinType::Bool))
  3899. PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
  3900. else
  3901. IntegerValue.toString(PrettyTargetValue);
  3902. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  3903. << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
  3904. << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
  3905. }
  3906. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  3907. if (!Range.Width) return "0";
  3908. llvm::APSInt ValueInRange = Value;
  3909. ValueInRange.setIsSigned(!Range.NonNegative);
  3910. ValueInRange = ValueInRange.trunc(Range.Width);
  3911. return ValueInRange.toString(10);
  3912. }
  3913. static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
  3914. if (!isa<ImplicitCastExpr>(Ex))
  3915. return false;
  3916. Expr *InnerE = Ex->IgnoreParenImpCasts();
  3917. const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
  3918. const Type *Source =
  3919. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  3920. if (Target->isDependentType())
  3921. return false;
  3922. const BuiltinType *FloatCandidateBT =
  3923. dyn_cast<BuiltinType>(ToBool ? Source : Target);
  3924. const Type *BoolCandidateType = ToBool ? Target : Source;
  3925. return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
  3926. FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
  3927. }
  3928. void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
  3929. SourceLocation CC) {
  3930. unsigned NumArgs = TheCall->getNumArgs();
  3931. for (unsigned i = 0; i < NumArgs; ++i) {
  3932. Expr *CurrA = TheCall->getArg(i);
  3933. if (!IsImplicitBoolFloatConversion(S, CurrA, true))
  3934. continue;
  3935. bool IsSwapped = ((i > 0) &&
  3936. IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
  3937. IsSwapped |= ((i < (NumArgs - 1)) &&
  3938. IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
  3939. if (IsSwapped) {
  3940. // Warn on this floating-point to bool conversion.
  3941. DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
  3942. CurrA->getType(), CC,
  3943. diag::warn_impcast_floating_point_to_bool);
  3944. }
  3945. }
  3946. }
  3947. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  3948. SourceLocation CC, bool *ICContext = 0) {
  3949. if (E->isTypeDependent() || E->isValueDependent()) return;
  3950. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  3951. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  3952. if (Source == Target) return;
  3953. if (Target->isDependentType()) return;
  3954. // If the conversion context location is invalid don't complain. We also
  3955. // don't want to emit a warning if the issue occurs from the expansion of
  3956. // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
  3957. // delay this check as long as possible. Once we detect we are in that
  3958. // scenario, we just return.
  3959. if (CC.isInvalid())
  3960. return;
  3961. // Diagnose implicit casts to bool.
  3962. if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
  3963. if (isa<StringLiteral>(E))
  3964. // Warn on string literal to bool. Checks for string literals in logical
  3965. // expressions, for instances, assert(0 && "error here"), is prevented
  3966. // by a check in AnalyzeImplicitConversions().
  3967. return DiagnoseImpCast(S, E, T, CC,
  3968. diag::warn_impcast_string_literal_to_bool);
  3969. if (Source->isFunctionType()) {
  3970. // Warn on function to bool. Checks free functions and static member
  3971. // functions. Weakly imported functions are excluded from the check,
  3972. // since it's common to test their value to check whether the linker
  3973. // found a definition for them.
  3974. ValueDecl *D = 0;
  3975. if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
  3976. D = R->getDecl();
  3977. } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
  3978. D = M->getMemberDecl();
  3979. }
  3980. if (D && !D->isWeak()) {
  3981. if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
  3982. S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
  3983. << F << E->getSourceRange() << SourceRange(CC);
  3984. S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
  3985. << FixItHint::CreateInsertion(E->getExprLoc(), "&");
  3986. QualType ReturnType;
  3987. UnresolvedSet<4> NonTemplateOverloads;
  3988. S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
  3989. if (!ReturnType.isNull()
  3990. && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
  3991. S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
  3992. << FixItHint::CreateInsertion(
  3993. S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
  3994. return;
  3995. }
  3996. }
  3997. }
  3998. }
  3999. // Strip vector types.
  4000. if (isa<VectorType>(Source)) {
  4001. if (!isa<VectorType>(Target)) {
  4002. if (S.SourceMgr.isInSystemMacro(CC))
  4003. return;
  4004. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  4005. }
  4006. // If the vector cast is cast between two vectors of the same size, it is
  4007. // a bitcast, not a conversion.
  4008. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  4009. return;
  4010. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  4011. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  4012. }
  4013. // Strip complex types.
  4014. if (isa<ComplexType>(Source)) {
  4015. if (!isa<ComplexType>(Target)) {
  4016. if (S.SourceMgr.isInSystemMacro(CC))
  4017. return;
  4018. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  4019. }
  4020. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  4021. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  4022. }
  4023. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  4024. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  4025. // If the source is floating point...
  4026. if (SourceBT && SourceBT->isFloatingPoint()) {
  4027. // ...and the target is floating point...
  4028. if (TargetBT && TargetBT->isFloatingPoint()) {
  4029. // ...then warn if we're dropping FP rank.
  4030. // Builtin FP kinds are ordered by increasing FP rank.
  4031. if (SourceBT->getKind() > TargetBT->getKind()) {
  4032. // Don't warn about float constants that are precisely
  4033. // representable in the target type.
  4034. Expr::EvalResult result;
  4035. if (E->EvaluateAsRValue(result, S.Context)) {
  4036. // Value might be a float, a float vector, or a float complex.
  4037. if (IsSameFloatAfterCast(result.Val,
  4038. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  4039. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  4040. return;
  4041. }
  4042. if (S.SourceMgr.isInSystemMacro(CC))
  4043. return;
  4044. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  4045. }
  4046. return;
  4047. }
  4048. // If the target is integral, always warn.
  4049. if (TargetBT && TargetBT->isInteger()) {
  4050. if (S.SourceMgr.isInSystemMacro(CC))
  4051. return;
  4052. Expr *InnerE = E->IgnoreParenImpCasts();
  4053. // We also want to warn on, e.g., "int i = -1.234"
  4054. if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
  4055. if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
  4056. InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
  4057. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  4058. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  4059. } else {
  4060. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  4061. }
  4062. }
  4063. // If the target is bool, warn if expr is a function or method call.
  4064. if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
  4065. isa<CallExpr>(E)) {
  4066. // Check last argument of function call to see if it is an
  4067. // implicit cast from a type matching the type the result
  4068. // is being cast to.
  4069. CallExpr *CEx = cast<CallExpr>(E);
  4070. unsigned NumArgs = CEx->getNumArgs();
  4071. if (NumArgs > 0) {
  4072. Expr *LastA = CEx->getArg(NumArgs - 1);
  4073. Expr *InnerE = LastA->IgnoreParenImpCasts();
  4074. const Type *InnerType =
  4075. S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
  4076. if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
  4077. // Warn on this floating-point to bool conversion
  4078. DiagnoseImpCast(S, E, T, CC,
  4079. diag::warn_impcast_floating_point_to_bool);
  4080. }
  4081. }
  4082. }
  4083. return;
  4084. }
  4085. if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
  4086. == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
  4087. && !Target->isBlockPointerType() && !Target->isMemberPointerType()) {
  4088. SourceLocation Loc = E->getSourceRange().getBegin();
  4089. if (Loc.isMacroID())
  4090. Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
  4091. if (!Loc.isMacroID() || CC.isMacroID())
  4092. S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
  4093. << T << clang::SourceRange(CC)
  4094. << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
  4095. }
  4096. if (!Source->isIntegerType() || !Target->isIntegerType())
  4097. return;
  4098. // TODO: remove this early return once the false positives for constant->bool
  4099. // in templates, macros, etc, are reduced or removed.
  4100. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  4101. return;
  4102. IntRange SourceRange = GetExprRange(S.Context, E);
  4103. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  4104. if (SourceRange.Width > TargetRange.Width) {
  4105. // If the source is a constant, use a default-on diagnostic.
  4106. // TODO: this should happen for bitfield stores, too.
  4107. llvm::APSInt Value(32);
  4108. if (E->isIntegerConstantExpr(Value, S.Context)) {
  4109. if (S.SourceMgr.isInSystemMacro(CC))
  4110. return;
  4111. std::string PrettySourceValue = Value.toString(10);
  4112. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  4113. S.DiagRuntimeBehavior(E->getExprLoc(), E,
  4114. S.PDiag(diag::warn_impcast_integer_precision_constant)
  4115. << PrettySourceValue << PrettyTargetValue
  4116. << E->getType() << T << E->getSourceRange()
  4117. << clang::SourceRange(CC));
  4118. return;
  4119. }
  4120. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  4121. if (S.SourceMgr.isInSystemMacro(CC))
  4122. return;
  4123. if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
  4124. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
  4125. /* pruneControlFlow */ true);
  4126. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  4127. }
  4128. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  4129. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  4130. SourceRange.Width == TargetRange.Width)) {
  4131. if (S.SourceMgr.isInSystemMacro(CC))
  4132. return;
  4133. unsigned DiagID = diag::warn_impcast_integer_sign;
  4134. // Traditionally, gcc has warned about this under -Wsign-compare.
  4135. // We also want to warn about it in -Wconversion.
  4136. // So if -Wconversion is off, use a completely identical diagnostic
  4137. // in the sign-compare group.
  4138. // The conditional-checking code will
  4139. if (ICContext) {
  4140. DiagID = diag::warn_impcast_integer_sign_conditional;
  4141. *ICContext = true;
  4142. }
  4143. return DiagnoseImpCast(S, E, T, CC, DiagID);
  4144. }
  4145. // Diagnose conversions between different enumeration types.
  4146. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  4147. // type, to give us better diagnostics.
  4148. QualType SourceType = E->getType();
  4149. if (!S.getLangOpts().CPlusPlus) {
  4150. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  4151. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  4152. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  4153. SourceType = S.Context.getTypeDeclType(Enum);
  4154. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  4155. }
  4156. }
  4157. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  4158. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  4159. if ((SourceEnum->getDecl()->getIdentifier() ||
  4160. SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  4161. (TargetEnum->getDecl()->getIdentifier() ||
  4162. TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  4163. SourceEnum != TargetEnum) {
  4164. if (S.SourceMgr.isInSystemMacro(CC))
  4165. return;
  4166. return DiagnoseImpCast(S, E, SourceType, T, CC,
  4167. diag::warn_impcast_different_enum_types);
  4168. }
  4169. return;
  4170. }
  4171. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  4172. SourceLocation CC, QualType T);
  4173. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  4174. SourceLocation CC, bool &ICContext) {
  4175. E = E->IgnoreParenImpCasts();
  4176. if (isa<ConditionalOperator>(E))
  4177. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
  4178. AnalyzeImplicitConversions(S, E, CC);
  4179. if (E->getType() != T)
  4180. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  4181. return;
  4182. }
  4183. void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
  4184. SourceLocation CC, QualType T) {
  4185. AnalyzeImplicitConversions(S, E->getCond(), CC);
  4186. bool Suspicious = false;
  4187. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  4188. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  4189. // If -Wconversion would have warned about either of the candidates
  4190. // for a signedness conversion to the context type...
  4191. if (!Suspicious) return;
  4192. // ...but it's currently ignored...
  4193. if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
  4194. CC))
  4195. return;
  4196. // ...then check whether it would have warned about either of the
  4197. // candidates for a signedness conversion to the condition type.
  4198. if (E->getType() == T) return;
  4199. Suspicious = false;
  4200. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  4201. E->getType(), CC, &Suspicious);
  4202. if (!Suspicious)
  4203. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  4204. E->getType(), CC, &Suspicious);
  4205. }
  4206. /// AnalyzeImplicitConversions - Find and report any interesting
  4207. /// implicit conversions in the given expression. There are a couple
  4208. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  4209. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  4210. QualType T = OrigE->getType();
  4211. Expr *E = OrigE->IgnoreParenImpCasts();
  4212. if (E->isTypeDependent() || E->isValueDependent())
  4213. return;
  4214. // For conditional operators, we analyze the arguments as if they
  4215. // were being fed directly into the output.
  4216. if (isa<ConditionalOperator>(E)) {
  4217. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  4218. CheckConditionalOperator(S, CO, CC, T);
  4219. return;
  4220. }
  4221. // Check implicit argument conversions for function calls.
  4222. if (CallExpr *Call = dyn_cast<CallExpr>(E))
  4223. CheckImplicitArgumentConversions(S, Call, CC);
  4224. // Go ahead and check any implicit conversions we might have skipped.
  4225. // The non-canonical typecheck is just an optimization;
  4226. // CheckImplicitConversion will filter out dead implicit conversions.
  4227. if (E->getType() != T)
  4228. CheckImplicitConversion(S, E, T, CC);
  4229. // Now continue drilling into this expression.
  4230. // Skip past explicit casts.
  4231. if (isa<ExplicitCastExpr>(E)) {
  4232. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  4233. return AnalyzeImplicitConversions(S, E, CC);
  4234. }
  4235. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  4236. // Do a somewhat different check with comparison operators.
  4237. if (BO->isComparisonOp())
  4238. return AnalyzeComparison(S, BO);
  4239. // And with simple assignments.
  4240. if (BO->getOpcode() == BO_Assign)
  4241. return AnalyzeAssignment(S, BO);
  4242. }
  4243. // These break the otherwise-useful invariant below. Fortunately,
  4244. // we don't really need to recurse into them, because any internal
  4245. // expressions should have been analyzed already when they were
  4246. // built into statements.
  4247. if (isa<StmtExpr>(E)) return;
  4248. // Don't descend into unevaluated contexts.
  4249. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  4250. // Now just recurse over the expression's children.
  4251. CC = E->getExprLoc();
  4252. BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
  4253. bool IsLogicalOperator = BO && BO->isLogicalOp();
  4254. for (Stmt::child_range I = E->children(); I; ++I) {
  4255. Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
  4256. if (!ChildExpr)
  4257. continue;
  4258. if (IsLogicalOperator &&
  4259. isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
  4260. // Ignore checking string literals that are in logical operators.
  4261. continue;
  4262. AnalyzeImplicitConversions(S, ChildExpr, CC);
  4263. }
  4264. }
  4265. } // end anonymous namespace
  4266. /// Diagnoses "dangerous" implicit conversions within the given
  4267. /// expression (which is a full expression). Implements -Wconversion
  4268. /// and -Wsign-compare.
  4269. ///
  4270. /// \param CC the "context" location of the implicit conversion, i.e.
  4271. /// the most location of the syntactic entity requiring the implicit
  4272. /// conversion
  4273. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  4274. // Don't diagnose in unevaluated contexts.
  4275. if (isUnevaluatedContext())
  4276. return;
  4277. // Don't diagnose for value- or type-dependent expressions.
  4278. if (E->isTypeDependent() || E->isValueDependent())
  4279. return;
  4280. // Check for array bounds violations in cases where the check isn't triggered
  4281. // elsewhere for other Expr types (like BinaryOperators), e.g. when an
  4282. // ArraySubscriptExpr is on the RHS of a variable initialization.
  4283. CheckArrayAccess(E);
  4284. // This is not the right CC for (e.g.) a variable initialization.
  4285. AnalyzeImplicitConversions(*this, E, CC);
  4286. }
  4287. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  4288. FieldDecl *BitField,
  4289. Expr *Init) {
  4290. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  4291. }
  4292. /// CheckParmsForFunctionDef - Check that the parameters of the given
  4293. /// function are appropriate for the definition of a function. This
  4294. /// takes care of any checks that cannot be performed on the
  4295. /// declaration itself, e.g., that the types of each of the function
  4296. /// parameters are complete.
  4297. bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
  4298. bool CheckParameterNames) {
  4299. bool HasInvalidParm = false;
  4300. for (; P != PEnd; ++P) {
  4301. ParmVarDecl *Param = *P;
  4302. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  4303. // function declarator that is part of a function definition of
  4304. // that function shall not have incomplete type.
  4305. //
  4306. // This is also C++ [dcl.fct]p6.
  4307. if (!Param->isInvalidDecl() &&
  4308. RequireCompleteType(Param->getLocation(), Param->getType(),
  4309. diag::err_typecheck_decl_incomplete_type)) {
  4310. Param->setInvalidDecl();
  4311. HasInvalidParm = true;
  4312. }
  4313. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  4314. // declaration of each parameter shall include an identifier.
  4315. if (CheckParameterNames &&
  4316. Param->getIdentifier() == 0 &&
  4317. !Param->isImplicit() &&
  4318. !getLangOpts().CPlusPlus)
  4319. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  4320. // C99 6.7.5.3p12:
  4321. // If the function declarator is not part of a definition of that
  4322. // function, parameters may have incomplete type and may use the [*]
  4323. // notation in their sequences of declarator specifiers to specify
  4324. // variable length array types.
  4325. QualType PType = Param->getOriginalType();
  4326. if (const ArrayType *AT = Context.getAsArrayType(PType)) {
  4327. if (AT->getSizeModifier() == ArrayType::Star) {
  4328. // FIXME: This diagnosic should point the '[*]' if source-location
  4329. // information is added for it.
  4330. Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
  4331. }
  4332. }
  4333. }
  4334. return HasInvalidParm;
  4335. }
  4336. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  4337. /// pointer cast increases the alignment requirements.
  4338. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  4339. // This is actually a lot of work to potentially be doing on every
  4340. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  4341. if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
  4342. TRange.getBegin())
  4343. == DiagnosticsEngine::Ignored)
  4344. return;
  4345. // Ignore dependent types.
  4346. if (T->isDependentType() || Op->getType()->isDependentType())
  4347. return;
  4348. // Require that the destination be a pointer type.
  4349. const PointerType *DestPtr = T->getAs<PointerType>();
  4350. if (!DestPtr) return;
  4351. // If the destination has alignment 1, we're done.
  4352. QualType DestPointee = DestPtr->getPointeeType();
  4353. if (DestPointee->isIncompleteType()) return;
  4354. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  4355. if (DestAlign.isOne()) return;
  4356. // Require that the source be a pointer type.
  4357. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  4358. if (!SrcPtr) return;
  4359. QualType SrcPointee = SrcPtr->getPointeeType();
  4360. // Whitelist casts from cv void*. We already implicitly
  4361. // whitelisted casts to cv void*, since they have alignment 1.
  4362. // Also whitelist casts involving incomplete types, which implicitly
  4363. // includes 'void'.
  4364. if (SrcPointee->isIncompleteType()) return;
  4365. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  4366. if (SrcAlign >= DestAlign) return;
  4367. Diag(TRange.getBegin(), diag::warn_cast_align)
  4368. << Op->getType() << T
  4369. << static_cast<unsigned>(SrcAlign.getQuantity())
  4370. << static_cast<unsigned>(DestAlign.getQuantity())
  4371. << TRange << Op->getSourceRange();
  4372. }
  4373. static const Type* getElementType(const Expr *BaseExpr) {
  4374. const Type* EltType = BaseExpr->getType().getTypePtr();
  4375. if (EltType->isAnyPointerType())
  4376. return EltType->getPointeeType().getTypePtr();
  4377. else if (EltType->isArrayType())
  4378. return EltType->getBaseElementTypeUnsafe();
  4379. return EltType;
  4380. }
  4381. /// \brief Check whether this array fits the idiom of a size-one tail padded
  4382. /// array member of a struct.
  4383. ///
  4384. /// We avoid emitting out-of-bounds access warnings for such arrays as they are
  4385. /// commonly used to emulate flexible arrays in C89 code.
  4386. static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
  4387. const NamedDecl *ND) {
  4388. if (Size != 1 || !ND) return false;
  4389. const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
  4390. if (!FD) return false;
  4391. // Don't consider sizes resulting from macro expansions or template argument
  4392. // substitution to form C89 tail-padded arrays.
  4393. TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
  4394. while (TInfo) {
  4395. TypeLoc TL = TInfo->getTypeLoc();
  4396. // Look through typedefs.
  4397. const TypedefTypeLoc *TTL = dyn_cast<TypedefTypeLoc>(&TL);
  4398. if (TTL) {
  4399. const TypedefNameDecl *TDL = TTL->getTypedefNameDecl();
  4400. TInfo = TDL->getTypeSourceInfo();
  4401. continue;
  4402. }
  4403. ConstantArrayTypeLoc CTL = cast<ConstantArrayTypeLoc>(TL);
  4404. const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
  4405. if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
  4406. return false;
  4407. break;
  4408. }
  4409. const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
  4410. if (!RD) return false;
  4411. if (RD->isUnion()) return false;
  4412. if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
  4413. if (!CRD->isStandardLayout()) return false;
  4414. }
  4415. // See if this is the last field decl in the record.
  4416. const Decl *D = FD;
  4417. while ((D = D->getNextDeclInContext()))
  4418. if (isa<FieldDecl>(D))
  4419. return false;
  4420. return true;
  4421. }
  4422. void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
  4423. const ArraySubscriptExpr *ASE,
  4424. bool AllowOnePastEnd, bool IndexNegated) {
  4425. IndexExpr = IndexExpr->IgnoreParenImpCasts();
  4426. if (IndexExpr->isValueDependent())
  4427. return;
  4428. const Type *EffectiveType = getElementType(BaseExpr);
  4429. BaseExpr = BaseExpr->IgnoreParenCasts();
  4430. const ConstantArrayType *ArrayTy =
  4431. Context.getAsConstantArrayType(BaseExpr->getType());
  4432. if (!ArrayTy)
  4433. return;
  4434. llvm::APSInt index;
  4435. if (!IndexExpr->EvaluateAsInt(index, Context))
  4436. return;
  4437. if (IndexNegated)
  4438. index = -index;
  4439. const NamedDecl *ND = NULL;
  4440. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  4441. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  4442. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  4443. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  4444. if (index.isUnsigned() || !index.isNegative()) {
  4445. llvm::APInt size = ArrayTy->getSize();
  4446. if (!size.isStrictlyPositive())
  4447. return;
  4448. const Type* BaseType = getElementType(BaseExpr);
  4449. if (BaseType != EffectiveType) {
  4450. // Make sure we're comparing apples to apples when comparing index to size
  4451. uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
  4452. uint64_t array_typesize = Context.getTypeSize(BaseType);
  4453. // Handle ptrarith_typesize being zero, such as when casting to void*
  4454. if (!ptrarith_typesize) ptrarith_typesize = 1;
  4455. if (ptrarith_typesize != array_typesize) {
  4456. // There's a cast to a different size type involved
  4457. uint64_t ratio = array_typesize / ptrarith_typesize;
  4458. // TODO: Be smarter about handling cases where array_typesize is not a
  4459. // multiple of ptrarith_typesize
  4460. if (ptrarith_typesize * ratio == array_typesize)
  4461. size *= llvm::APInt(size.getBitWidth(), ratio);
  4462. }
  4463. }
  4464. if (size.getBitWidth() > index.getBitWidth())
  4465. index = index.zext(size.getBitWidth());
  4466. else if (size.getBitWidth() < index.getBitWidth())
  4467. size = size.zext(index.getBitWidth());
  4468. // For array subscripting the index must be less than size, but for pointer
  4469. // arithmetic also allow the index (offset) to be equal to size since
  4470. // computing the next address after the end of the array is legal and
  4471. // commonly done e.g. in C++ iterators and range-based for loops.
  4472. if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
  4473. return;
  4474. // Also don't warn for arrays of size 1 which are members of some
  4475. // structure. These are often used to approximate flexible arrays in C89
  4476. // code.
  4477. if (IsTailPaddedMemberArray(*this, size, ND))
  4478. return;
  4479. // Suppress the warning if the subscript expression (as identified by the
  4480. // ']' location) and the index expression are both from macro expansions
  4481. // within a system header.
  4482. if (ASE) {
  4483. SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
  4484. ASE->getRBracketLoc());
  4485. if (SourceMgr.isInSystemHeader(RBracketLoc)) {
  4486. SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
  4487. IndexExpr->getLocStart());
  4488. if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
  4489. return;
  4490. }
  4491. }
  4492. unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
  4493. if (ASE)
  4494. DiagID = diag::warn_array_index_exceeds_bounds;
  4495. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  4496. PDiag(DiagID) << index.toString(10, true)
  4497. << size.toString(10, true)
  4498. << (unsigned)size.getLimitedValue(~0U)
  4499. << IndexExpr->getSourceRange());
  4500. } else {
  4501. unsigned DiagID = diag::warn_array_index_precedes_bounds;
  4502. if (!ASE) {
  4503. DiagID = diag::warn_ptr_arith_precedes_bounds;
  4504. if (index.isNegative()) index = -index;
  4505. }
  4506. DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
  4507. PDiag(DiagID) << index.toString(10, true)
  4508. << IndexExpr->getSourceRange());
  4509. }
  4510. if (!ND) {
  4511. // Try harder to find a NamedDecl to point at in the note.
  4512. while (const ArraySubscriptExpr *ASE =
  4513. dyn_cast<ArraySubscriptExpr>(BaseExpr))
  4514. BaseExpr = ASE->getBase()->IgnoreParenCasts();
  4515. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  4516. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  4517. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  4518. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  4519. }
  4520. if (ND)
  4521. DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  4522. PDiag(diag::note_array_index_out_of_bounds)
  4523. << ND->getDeclName());
  4524. }
  4525. void Sema::CheckArrayAccess(const Expr *expr) {
  4526. int AllowOnePastEnd = 0;
  4527. while (expr) {
  4528. expr = expr->IgnoreParenImpCasts();
  4529. switch (expr->getStmtClass()) {
  4530. case Stmt::ArraySubscriptExprClass: {
  4531. const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
  4532. CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
  4533. AllowOnePastEnd > 0);
  4534. return;
  4535. }
  4536. case Stmt::UnaryOperatorClass: {
  4537. // Only unwrap the * and & unary operators
  4538. const UnaryOperator *UO = cast<UnaryOperator>(expr);
  4539. expr = UO->getSubExpr();
  4540. switch (UO->getOpcode()) {
  4541. case UO_AddrOf:
  4542. AllowOnePastEnd++;
  4543. break;
  4544. case UO_Deref:
  4545. AllowOnePastEnd--;
  4546. break;
  4547. default:
  4548. return;
  4549. }
  4550. break;
  4551. }
  4552. case Stmt::ConditionalOperatorClass: {
  4553. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  4554. if (const Expr *lhs = cond->getLHS())
  4555. CheckArrayAccess(lhs);
  4556. if (const Expr *rhs = cond->getRHS())
  4557. CheckArrayAccess(rhs);
  4558. return;
  4559. }
  4560. default:
  4561. return;
  4562. }
  4563. }
  4564. }
  4565. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  4566. namespace {
  4567. struct RetainCycleOwner {
  4568. RetainCycleOwner() : Variable(0), Indirect(false) {}
  4569. VarDecl *Variable;
  4570. SourceRange Range;
  4571. SourceLocation Loc;
  4572. bool Indirect;
  4573. void setLocsFrom(Expr *e) {
  4574. Loc = e->getExprLoc();
  4575. Range = e->getSourceRange();
  4576. }
  4577. };
  4578. }
  4579. /// Consider whether capturing the given variable can possibly lead to
  4580. /// a retain cycle.
  4581. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  4582. // In ARC, it's captured strongly iff the variable has __strong
  4583. // lifetime. In MRR, it's captured strongly if the variable is
  4584. // __block and has an appropriate type.
  4585. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  4586. return false;
  4587. owner.Variable = var;
  4588. owner.setLocsFrom(ref);
  4589. return true;
  4590. }
  4591. static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
  4592. while (true) {
  4593. e = e->IgnoreParens();
  4594. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  4595. switch (cast->getCastKind()) {
  4596. case CK_BitCast:
  4597. case CK_LValueBitCast:
  4598. case CK_LValueToRValue:
  4599. case CK_ARCReclaimReturnedObject:
  4600. e = cast->getSubExpr();
  4601. continue;
  4602. default:
  4603. return false;
  4604. }
  4605. }
  4606. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  4607. ObjCIvarDecl *ivar = ref->getDecl();
  4608. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  4609. return false;
  4610. // Try to find a retain cycle in the base.
  4611. if (!findRetainCycleOwner(S, ref->getBase(), owner))
  4612. return false;
  4613. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  4614. owner.Indirect = true;
  4615. return true;
  4616. }
  4617. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  4618. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  4619. if (!var) return false;
  4620. return considerVariable(var, ref, owner);
  4621. }
  4622. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  4623. if (member->isArrow()) return false;
  4624. // Don't count this as an indirect ownership.
  4625. e = member->getBase();
  4626. continue;
  4627. }
  4628. if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
  4629. // Only pay attention to pseudo-objects on property references.
  4630. ObjCPropertyRefExpr *pre
  4631. = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
  4632. ->IgnoreParens());
  4633. if (!pre) return false;
  4634. if (pre->isImplicitProperty()) return false;
  4635. ObjCPropertyDecl *property = pre->getExplicitProperty();
  4636. if (!property->isRetaining() &&
  4637. !(property->getPropertyIvarDecl() &&
  4638. property->getPropertyIvarDecl()->getType()
  4639. .getObjCLifetime() == Qualifiers::OCL_Strong))
  4640. return false;
  4641. owner.Indirect = true;
  4642. if (pre->isSuperReceiver()) {
  4643. owner.Variable = S.getCurMethodDecl()->getSelfDecl();
  4644. if (!owner.Variable)
  4645. return false;
  4646. owner.Loc = pre->getLocation();
  4647. owner.Range = pre->getSourceRange();
  4648. return true;
  4649. }
  4650. e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
  4651. ->getSourceExpr());
  4652. continue;
  4653. }
  4654. // Array ivars?
  4655. return false;
  4656. }
  4657. }
  4658. namespace {
  4659. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  4660. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  4661. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  4662. Variable(variable), Capturer(0) {}
  4663. VarDecl *Variable;
  4664. Expr *Capturer;
  4665. void VisitDeclRefExpr(DeclRefExpr *ref) {
  4666. if (ref->getDecl() == Variable && !Capturer)
  4667. Capturer = ref;
  4668. }
  4669. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  4670. if (Capturer) return;
  4671. Visit(ref->getBase());
  4672. if (Capturer && ref->isFreeIvar())
  4673. Capturer = ref;
  4674. }
  4675. void VisitBlockExpr(BlockExpr *block) {
  4676. // Look inside nested blocks
  4677. if (block->getBlockDecl()->capturesVariable(Variable))
  4678. Visit(block->getBlockDecl()->getBody());
  4679. }
  4680. void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
  4681. if (Capturer) return;
  4682. if (OVE->getSourceExpr())
  4683. Visit(OVE->getSourceExpr());
  4684. }
  4685. };
  4686. }
  4687. /// Check whether the given argument is a block which captures a
  4688. /// variable.
  4689. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  4690. assert(owner.Variable && owner.Loc.isValid());
  4691. e = e->IgnoreParenCasts();
  4692. BlockExpr *block = dyn_cast<BlockExpr>(e);
  4693. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  4694. return 0;
  4695. FindCaptureVisitor visitor(S.Context, owner.Variable);
  4696. visitor.Visit(block->getBlockDecl()->getBody());
  4697. return visitor.Capturer;
  4698. }
  4699. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  4700. RetainCycleOwner &owner) {
  4701. assert(capturer);
  4702. assert(owner.Variable && owner.Loc.isValid());
  4703. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  4704. << owner.Variable << capturer->getSourceRange();
  4705. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  4706. << owner.Indirect << owner.Range;
  4707. }
  4708. /// Check for a keyword selector that starts with the word 'add' or
  4709. /// 'set'.
  4710. static bool isSetterLikeSelector(Selector sel) {
  4711. if (sel.isUnarySelector()) return false;
  4712. StringRef str = sel.getNameForSlot(0);
  4713. while (!str.empty() && str.front() == '_') str = str.substr(1);
  4714. if (str.startswith("set"))
  4715. str = str.substr(3);
  4716. else if (str.startswith("add")) {
  4717. // Specially whitelist 'addOperationWithBlock:'.
  4718. if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
  4719. return false;
  4720. str = str.substr(3);
  4721. }
  4722. else
  4723. return false;
  4724. if (str.empty()) return true;
  4725. return !islower(str.front());
  4726. }
  4727. /// Check a message send to see if it's likely to cause a retain cycle.
  4728. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  4729. // Only check instance methods whose selector looks like a setter.
  4730. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  4731. return;
  4732. // Try to find a variable that the receiver is strongly owned by.
  4733. RetainCycleOwner owner;
  4734. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  4735. if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
  4736. return;
  4737. } else {
  4738. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  4739. owner.Variable = getCurMethodDecl()->getSelfDecl();
  4740. owner.Loc = msg->getSuperLoc();
  4741. owner.Range = msg->getSuperLoc();
  4742. }
  4743. // Check whether the receiver is captured by any of the arguments.
  4744. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  4745. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  4746. return diagnoseRetainCycle(*this, capturer, owner);
  4747. }
  4748. /// Check a property assign to see if it's likely to cause a retain cycle.
  4749. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  4750. RetainCycleOwner owner;
  4751. if (!findRetainCycleOwner(*this, receiver, owner))
  4752. return;
  4753. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  4754. diagnoseRetainCycle(*this, capturer, owner);
  4755. }
  4756. bool Sema::checkUnsafeAssigns(SourceLocation Loc,
  4757. QualType LHS, Expr *RHS) {
  4758. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  4759. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  4760. return false;
  4761. // strip off any implicit cast added to get to the one arc-specific
  4762. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4763. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4764. Diag(Loc, diag::warn_arc_retained_assign)
  4765. << (LT == Qualifiers::OCL_ExplicitNone) << 1
  4766. << RHS->getSourceRange();
  4767. return true;
  4768. }
  4769. RHS = cast->getSubExpr();
  4770. }
  4771. return false;
  4772. }
  4773. void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
  4774. Expr *LHS, Expr *RHS) {
  4775. QualType LHSType;
  4776. // PropertyRef on LHS type need be directly obtained from
  4777. // its declaration as it has a PsuedoType.
  4778. ObjCPropertyRefExpr *PRE
  4779. = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
  4780. if (PRE && !PRE->isImplicitProperty()) {
  4781. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  4782. if (PD)
  4783. LHSType = PD->getType();
  4784. }
  4785. if (LHSType.isNull())
  4786. LHSType = LHS->getType();
  4787. if (checkUnsafeAssigns(Loc, LHSType, RHS))
  4788. return;
  4789. Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
  4790. // FIXME. Check for other life times.
  4791. if (LT != Qualifiers::OCL_None)
  4792. return;
  4793. if (PRE) {
  4794. if (PRE->isImplicitProperty())
  4795. return;
  4796. const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
  4797. if (!PD)
  4798. return;
  4799. unsigned Attributes = PD->getPropertyAttributes();
  4800. if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
  4801. // when 'assign' attribute was not explicitly specified
  4802. // by user, ignore it and rely on property type itself
  4803. // for lifetime info.
  4804. unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
  4805. if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
  4806. LHSType->isObjCRetainableType())
  4807. return;
  4808. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4809. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4810. Diag(Loc, diag::warn_arc_retained_property_assign)
  4811. << RHS->getSourceRange();
  4812. return;
  4813. }
  4814. RHS = cast->getSubExpr();
  4815. }
  4816. }
  4817. else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
  4818. while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
  4819. if (cast->getCastKind() == CK_ARCConsumeObject) {
  4820. Diag(Loc, diag::warn_arc_retained_assign)
  4821. << 0 << 0<< RHS->getSourceRange();
  4822. return;
  4823. }
  4824. RHS = cast->getSubExpr();
  4825. }
  4826. }
  4827. }
  4828. }
  4829. //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
  4830. namespace {
  4831. bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
  4832. SourceLocation StmtLoc,
  4833. const NullStmt *Body) {
  4834. // Do not warn if the body is a macro that expands to nothing, e.g:
  4835. //
  4836. // #define CALL(x)
  4837. // if (condition)
  4838. // CALL(0);
  4839. //
  4840. if (Body->hasLeadingEmptyMacro())
  4841. return false;
  4842. // Get line numbers of statement and body.
  4843. bool StmtLineInvalid;
  4844. unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
  4845. &StmtLineInvalid);
  4846. if (StmtLineInvalid)
  4847. return false;
  4848. bool BodyLineInvalid;
  4849. unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
  4850. &BodyLineInvalid);
  4851. if (BodyLineInvalid)
  4852. return false;
  4853. // Warn if null statement and body are on the same line.
  4854. if (StmtLine != BodyLine)
  4855. return false;
  4856. return true;
  4857. }
  4858. } // Unnamed namespace
  4859. void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
  4860. const Stmt *Body,
  4861. unsigned DiagID) {
  4862. // Since this is a syntactic check, don't emit diagnostic for template
  4863. // instantiations, this just adds noise.
  4864. if (CurrentInstantiationScope)
  4865. return;
  4866. // The body should be a null statement.
  4867. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  4868. if (!NBody)
  4869. return;
  4870. // Do the usual checks.
  4871. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  4872. return;
  4873. Diag(NBody->getSemiLoc(), DiagID);
  4874. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  4875. }
  4876. void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
  4877. const Stmt *PossibleBody) {
  4878. assert(!CurrentInstantiationScope); // Ensured by caller
  4879. SourceLocation StmtLoc;
  4880. const Stmt *Body;
  4881. unsigned DiagID;
  4882. if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
  4883. StmtLoc = FS->getRParenLoc();
  4884. Body = FS->getBody();
  4885. DiagID = diag::warn_empty_for_body;
  4886. } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
  4887. StmtLoc = WS->getCond()->getSourceRange().getEnd();
  4888. Body = WS->getBody();
  4889. DiagID = diag::warn_empty_while_body;
  4890. } else
  4891. return; // Neither `for' nor `while'.
  4892. // The body should be a null statement.
  4893. const NullStmt *NBody = dyn_cast<NullStmt>(Body);
  4894. if (!NBody)
  4895. return;
  4896. // Skip expensive checks if diagnostic is disabled.
  4897. if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
  4898. DiagnosticsEngine::Ignored)
  4899. return;
  4900. // Do the usual checks.
  4901. if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
  4902. return;
  4903. // `for(...);' and `while(...);' are popular idioms, so in order to keep
  4904. // noise level low, emit diagnostics only if for/while is followed by a
  4905. // CompoundStmt, e.g.:
  4906. // for (int i = 0; i < n; i++);
  4907. // {
  4908. // a(i);
  4909. // }
  4910. // or if for/while is followed by a statement with more indentation
  4911. // than for/while itself:
  4912. // for (int i = 0; i < n; i++);
  4913. // a(i);
  4914. bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
  4915. if (!ProbableTypo) {
  4916. bool BodyColInvalid;
  4917. unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
  4918. PossibleBody->getLocStart(),
  4919. &BodyColInvalid);
  4920. if (BodyColInvalid)
  4921. return;
  4922. bool StmtColInvalid;
  4923. unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
  4924. S->getLocStart(),
  4925. &StmtColInvalid);
  4926. if (StmtColInvalid)
  4927. return;
  4928. if (BodyCol > StmtCol)
  4929. ProbableTypo = true;
  4930. }
  4931. if (ProbableTypo) {
  4932. Diag(NBody->getSemiLoc(), DiagID);
  4933. Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
  4934. }
  4935. }
  4936. //===--- Layout compatibility ----------------------------------------------//
  4937. namespace {
  4938. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
  4939. /// \brief Check if two enumeration types are layout-compatible.
  4940. bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
  4941. // C++11 [dcl.enum] p8:
  4942. // Two enumeration types are layout-compatible if they have the same
  4943. // underlying type.
  4944. return ED1->isComplete() && ED2->isComplete() &&
  4945. C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
  4946. }
  4947. /// \brief Check if two fields are layout-compatible.
  4948. bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
  4949. if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
  4950. return false;
  4951. if (Field1->isBitField() != Field2->isBitField())
  4952. return false;
  4953. if (Field1->isBitField()) {
  4954. // Make sure that the bit-fields are the same length.
  4955. unsigned Bits1 = Field1->getBitWidthValue(C);
  4956. unsigned Bits2 = Field2->getBitWidthValue(C);
  4957. if (Bits1 != Bits2)
  4958. return false;
  4959. }
  4960. return true;
  4961. }
  4962. /// \brief Check if two standard-layout structs are layout-compatible.
  4963. /// (C++11 [class.mem] p17)
  4964. bool isLayoutCompatibleStruct(ASTContext &C,
  4965. RecordDecl *RD1,
  4966. RecordDecl *RD2) {
  4967. // If both records are C++ classes, check that base classes match.
  4968. if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
  4969. // If one of records is a CXXRecordDecl we are in C++ mode,
  4970. // thus the other one is a CXXRecordDecl, too.
  4971. const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
  4972. // Check number of base classes.
  4973. if (D1CXX->getNumBases() != D2CXX->getNumBases())
  4974. return false;
  4975. // Check the base classes.
  4976. for (CXXRecordDecl::base_class_const_iterator
  4977. Base1 = D1CXX->bases_begin(),
  4978. BaseEnd1 = D1CXX->bases_end(),
  4979. Base2 = D2CXX->bases_begin();
  4980. Base1 != BaseEnd1;
  4981. ++Base1, ++Base2) {
  4982. if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
  4983. return false;
  4984. }
  4985. } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
  4986. // If only RD2 is a C++ class, it should have zero base classes.
  4987. if (D2CXX->getNumBases() > 0)
  4988. return false;
  4989. }
  4990. // Check the fields.
  4991. RecordDecl::field_iterator Field2 = RD2->field_begin(),
  4992. Field2End = RD2->field_end(),
  4993. Field1 = RD1->field_begin(),
  4994. Field1End = RD1->field_end();
  4995. for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
  4996. if (!isLayoutCompatible(C, *Field1, *Field2))
  4997. return false;
  4998. }
  4999. if (Field1 != Field1End || Field2 != Field2End)
  5000. return false;
  5001. return true;
  5002. }
  5003. /// \brief Check if two standard-layout unions are layout-compatible.
  5004. /// (C++11 [class.mem] p18)
  5005. bool isLayoutCompatibleUnion(ASTContext &C,
  5006. RecordDecl *RD1,
  5007. RecordDecl *RD2) {
  5008. llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
  5009. for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
  5010. Field2End = RD2->field_end();
  5011. Field2 != Field2End; ++Field2) {
  5012. UnmatchedFields.insert(*Field2);
  5013. }
  5014. for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
  5015. Field1End = RD1->field_end();
  5016. Field1 != Field1End; ++Field1) {
  5017. llvm::SmallPtrSet<FieldDecl *, 8>::iterator
  5018. I = UnmatchedFields.begin(),
  5019. E = UnmatchedFields.end();
  5020. for ( ; I != E; ++I) {
  5021. if (isLayoutCompatible(C, *Field1, *I)) {
  5022. bool Result = UnmatchedFields.erase(*I);
  5023. (void) Result;
  5024. assert(Result);
  5025. break;
  5026. }
  5027. }
  5028. if (I == E)
  5029. return false;
  5030. }
  5031. return UnmatchedFields.empty();
  5032. }
  5033. bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
  5034. if (RD1->isUnion() != RD2->isUnion())
  5035. return false;
  5036. if (RD1->isUnion())
  5037. return isLayoutCompatibleUnion(C, RD1, RD2);
  5038. else
  5039. return isLayoutCompatibleStruct(C, RD1, RD2);
  5040. }
  5041. /// \brief Check if two types are layout-compatible in C++11 sense.
  5042. bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
  5043. if (T1.isNull() || T2.isNull())
  5044. return false;
  5045. // C++11 [basic.types] p11:
  5046. // If two types T1 and T2 are the same type, then T1 and T2 are
  5047. // layout-compatible types.
  5048. if (C.hasSameType(T1, T2))
  5049. return true;
  5050. T1 = T1.getCanonicalType().getUnqualifiedType();
  5051. T2 = T2.getCanonicalType().getUnqualifiedType();
  5052. const Type::TypeClass TC1 = T1->getTypeClass();
  5053. const Type::TypeClass TC2 = T2->getTypeClass();
  5054. if (TC1 != TC2)
  5055. return false;
  5056. if (TC1 == Type::Enum) {
  5057. return isLayoutCompatible(C,
  5058. cast<EnumType>(T1)->getDecl(),
  5059. cast<EnumType>(T2)->getDecl());
  5060. } else if (TC1 == Type::Record) {
  5061. if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
  5062. return false;
  5063. return isLayoutCompatible(C,
  5064. cast<RecordType>(T1)->getDecl(),
  5065. cast<RecordType>(T2)->getDecl());
  5066. }
  5067. return false;
  5068. }
  5069. }
  5070. //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
  5071. namespace {
  5072. /// \brief Given a type tag expression find the type tag itself.
  5073. ///
  5074. /// \param TypeExpr Type tag expression, as it appears in user's code.
  5075. ///
  5076. /// \param VD Declaration of an identifier that appears in a type tag.
  5077. ///
  5078. /// \param MagicValue Type tag magic value.
  5079. bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
  5080. const ValueDecl **VD, uint64_t *MagicValue) {
  5081. while(true) {
  5082. if (!TypeExpr)
  5083. return false;
  5084. TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
  5085. switch (TypeExpr->getStmtClass()) {
  5086. case Stmt::UnaryOperatorClass: {
  5087. const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
  5088. if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
  5089. TypeExpr = UO->getSubExpr();
  5090. continue;
  5091. }
  5092. return false;
  5093. }
  5094. case Stmt::DeclRefExprClass: {
  5095. const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
  5096. *VD = DRE->getDecl();
  5097. return true;
  5098. }
  5099. case Stmt::IntegerLiteralClass: {
  5100. const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
  5101. llvm::APInt MagicValueAPInt = IL->getValue();
  5102. if (MagicValueAPInt.getActiveBits() <= 64) {
  5103. *MagicValue = MagicValueAPInt.getZExtValue();
  5104. return true;
  5105. } else
  5106. return false;
  5107. }
  5108. case Stmt::BinaryConditionalOperatorClass:
  5109. case Stmt::ConditionalOperatorClass: {
  5110. const AbstractConditionalOperator *ACO =
  5111. cast<AbstractConditionalOperator>(TypeExpr);
  5112. bool Result;
  5113. if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
  5114. if (Result)
  5115. TypeExpr = ACO->getTrueExpr();
  5116. else
  5117. TypeExpr = ACO->getFalseExpr();
  5118. continue;
  5119. }
  5120. return false;
  5121. }
  5122. case Stmt::BinaryOperatorClass: {
  5123. const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
  5124. if (BO->getOpcode() == BO_Comma) {
  5125. TypeExpr = BO->getRHS();
  5126. continue;
  5127. }
  5128. return false;
  5129. }
  5130. default:
  5131. return false;
  5132. }
  5133. }
  5134. }
  5135. /// \brief Retrieve the C type corresponding to type tag TypeExpr.
  5136. ///
  5137. /// \param TypeExpr Expression that specifies a type tag.
  5138. ///
  5139. /// \param MagicValues Registered magic values.
  5140. ///
  5141. /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
  5142. /// kind.
  5143. ///
  5144. /// \param TypeInfo Information about the corresponding C type.
  5145. ///
  5146. /// \returns true if the corresponding C type was found.
  5147. bool GetMatchingCType(
  5148. const IdentifierInfo *ArgumentKind,
  5149. const Expr *TypeExpr, const ASTContext &Ctx,
  5150. const llvm::DenseMap<Sema::TypeTagMagicValue,
  5151. Sema::TypeTagData> *MagicValues,
  5152. bool &FoundWrongKind,
  5153. Sema::TypeTagData &TypeInfo) {
  5154. FoundWrongKind = false;
  5155. // Variable declaration that has type_tag_for_datatype attribute.
  5156. const ValueDecl *VD = NULL;
  5157. uint64_t MagicValue;
  5158. if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
  5159. return false;
  5160. if (VD) {
  5161. for (specific_attr_iterator<TypeTagForDatatypeAttr>
  5162. I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
  5163. E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
  5164. I != E; ++I) {
  5165. if (I->getArgumentKind() != ArgumentKind) {
  5166. FoundWrongKind = true;
  5167. return false;
  5168. }
  5169. TypeInfo.Type = I->getMatchingCType();
  5170. TypeInfo.LayoutCompatible = I->getLayoutCompatible();
  5171. TypeInfo.MustBeNull = I->getMustBeNull();
  5172. return true;
  5173. }
  5174. return false;
  5175. }
  5176. if (!MagicValues)
  5177. return false;
  5178. llvm::DenseMap<Sema::TypeTagMagicValue,
  5179. Sema::TypeTagData>::const_iterator I =
  5180. MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
  5181. if (I == MagicValues->end())
  5182. return false;
  5183. TypeInfo = I->second;
  5184. return true;
  5185. }
  5186. } // unnamed namespace
  5187. void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
  5188. uint64_t MagicValue, QualType Type,
  5189. bool LayoutCompatible,
  5190. bool MustBeNull) {
  5191. if (!TypeTagForDatatypeMagicValues)
  5192. TypeTagForDatatypeMagicValues.reset(
  5193. new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
  5194. TypeTagMagicValue Magic(ArgumentKind, MagicValue);
  5195. (*TypeTagForDatatypeMagicValues)[Magic] =
  5196. TypeTagData(Type, LayoutCompatible, MustBeNull);
  5197. }
  5198. namespace {
  5199. bool IsSameCharType(QualType T1, QualType T2) {
  5200. const BuiltinType *BT1 = T1->getAs<BuiltinType>();
  5201. if (!BT1)
  5202. return false;
  5203. const BuiltinType *BT2 = T2->getAs<BuiltinType>();
  5204. if (!BT2)
  5205. return false;
  5206. BuiltinType::Kind T1Kind = BT1->getKind();
  5207. BuiltinType::Kind T2Kind = BT2->getKind();
  5208. return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
  5209. (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
  5210. (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
  5211. (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
  5212. }
  5213. } // unnamed namespace
  5214. void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
  5215. const Expr * const *ExprArgs) {
  5216. const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
  5217. bool IsPointerAttr = Attr->getIsPointer();
  5218. const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
  5219. bool FoundWrongKind;
  5220. TypeTagData TypeInfo;
  5221. if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
  5222. TypeTagForDatatypeMagicValues.get(),
  5223. FoundWrongKind, TypeInfo)) {
  5224. if (FoundWrongKind)
  5225. Diag(TypeTagExpr->getExprLoc(),
  5226. diag::warn_type_tag_for_datatype_wrong_kind)
  5227. << TypeTagExpr->getSourceRange();
  5228. return;
  5229. }
  5230. const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
  5231. if (IsPointerAttr) {
  5232. // Skip implicit cast of pointer to `void *' (as a function argument).
  5233. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
  5234. if (ICE->getType()->isVoidPointerType())
  5235. ArgumentExpr = ICE->getSubExpr();
  5236. }
  5237. QualType ArgumentType = ArgumentExpr->getType();
  5238. // Passing a `void*' pointer shouldn't trigger a warning.
  5239. if (IsPointerAttr && ArgumentType->isVoidPointerType())
  5240. return;
  5241. if (TypeInfo.MustBeNull) {
  5242. // Type tag with matching void type requires a null pointer.
  5243. if (!ArgumentExpr->isNullPointerConstant(Context,
  5244. Expr::NPC_ValueDependentIsNotNull)) {
  5245. Diag(ArgumentExpr->getExprLoc(),
  5246. diag::warn_type_safety_null_pointer_required)
  5247. << ArgumentKind->getName()
  5248. << ArgumentExpr->getSourceRange()
  5249. << TypeTagExpr->getSourceRange();
  5250. }
  5251. return;
  5252. }
  5253. QualType RequiredType = TypeInfo.Type;
  5254. if (IsPointerAttr)
  5255. RequiredType = Context.getPointerType(RequiredType);
  5256. bool mismatch = false;
  5257. if (!TypeInfo.LayoutCompatible) {
  5258. mismatch = !Context.hasSameType(ArgumentType, RequiredType);
  5259. // C++11 [basic.fundamental] p1:
  5260. // Plain char, signed char, and unsigned char are three distinct types.
  5261. //
  5262. // But we treat plain `char' as equivalent to `signed char' or `unsigned
  5263. // char' depending on the current char signedness mode.
  5264. if (mismatch)
  5265. if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
  5266. RequiredType->getPointeeType())) ||
  5267. (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
  5268. mismatch = false;
  5269. } else
  5270. if (IsPointerAttr)
  5271. mismatch = !isLayoutCompatible(Context,
  5272. ArgumentType->getPointeeType(),
  5273. RequiredType->getPointeeType());
  5274. else
  5275. mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
  5276. if (mismatch)
  5277. Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
  5278. << ArgumentType << ArgumentKind->getName()
  5279. << TypeInfo.LayoutCompatible << RequiredType
  5280. << ArgumentExpr->getSourceRange()
  5281. << TypeTagExpr->getSourceRange();
  5282. }