SemaChecking.cpp 132 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641
  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/Sema.h"
  15. #include "clang/Sema/SemaInternal.h"
  16. #include "clang/Sema/ScopeInfo.h"
  17. #include "clang/Analysis/Analyses/FormatString.h"
  18. #include "clang/AST/ASTContext.h"
  19. #include "clang/AST/CharUnits.h"
  20. #include "clang/AST/DeclCXX.h"
  21. #include "clang/AST/DeclObjC.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/ExprObjC.h"
  24. #include "clang/AST/EvaluatedExprVisitor.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/StmtCXX.h"
  27. #include "clang/AST/StmtObjC.h"
  28. #include "clang/Lex/Preprocessor.h"
  29. #include "llvm/ADT/BitVector.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include "llvm/Support/raw_ostream.h"
  32. #include "clang/Basic/TargetBuiltins.h"
  33. #include "clang/Basic/TargetInfo.h"
  34. #include "clang/Basic/ConvertUTF.h"
  35. #include <limits>
  36. using namespace clang;
  37. using namespace sema;
  38. SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
  39. unsigned ByteNo) const {
  40. return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
  41. PP.getLangOptions(), PP.getTargetInfo());
  42. }
  43. /// CheckablePrintfAttr - does a function call have a "printf" attribute
  44. /// and arguments that merit checking?
  45. bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
  46. if (Format->getType() == "printf") return true;
  47. if (Format->getType() == "printf0") {
  48. // printf0 allows null "format" string; if so don't check format/args
  49. unsigned format_idx = Format->getFormatIdx() - 1;
  50. // Does the index refer to the implicit object argument?
  51. if (isa<CXXMemberCallExpr>(TheCall)) {
  52. if (format_idx == 0)
  53. return false;
  54. --format_idx;
  55. }
  56. if (format_idx < TheCall->getNumArgs()) {
  57. Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
  58. if (!Format->isNullPointerConstant(Context,
  59. Expr::NPC_ValueDependentIsNull))
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. /// Checks that a call expression's argument count is the desired number.
  66. /// This is useful when doing custom type-checking. Returns true on error.
  67. static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
  68. unsigned argCount = call->getNumArgs();
  69. if (argCount == desiredArgCount) return false;
  70. if (argCount < desiredArgCount)
  71. return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
  72. << 0 /*function call*/ << desiredArgCount << argCount
  73. << call->getSourceRange();
  74. // Highlight all the excess arguments.
  75. SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
  76. call->getArg(argCount - 1)->getLocEnd());
  77. return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
  78. << 0 /*function call*/ << desiredArgCount << argCount
  79. << call->getArg(1)->getSourceRange();
  80. }
  81. ExprResult
  82. Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  83. ExprResult TheCallResult(Owned(TheCall));
  84. // Find out if any arguments are required to be integer constant expressions.
  85. unsigned ICEArguments = 0;
  86. ASTContext::GetBuiltinTypeError Error;
  87. Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
  88. if (Error != ASTContext::GE_None)
  89. ICEArguments = 0; // Don't diagnose previously diagnosed errors.
  90. // If any arguments are required to be ICE's, check and diagnose.
  91. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
  92. // Skip arguments not required to be ICE's.
  93. if ((ICEArguments & (1 << ArgNo)) == 0) continue;
  94. llvm::APSInt Result;
  95. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  96. return true;
  97. ICEArguments &= ~(1 << ArgNo);
  98. }
  99. switch (BuiltinID) {
  100. case Builtin::BI__builtin___CFStringMakeConstantString:
  101. assert(TheCall->getNumArgs() == 1 &&
  102. "Wrong # arguments to builtin CFStringMakeConstantString");
  103. if (CheckObjCString(TheCall->getArg(0)))
  104. return ExprError();
  105. break;
  106. case Builtin::BI__builtin_stdarg_start:
  107. case Builtin::BI__builtin_va_start:
  108. if (SemaBuiltinVAStart(TheCall))
  109. return ExprError();
  110. break;
  111. case Builtin::BI__builtin_isgreater:
  112. case Builtin::BI__builtin_isgreaterequal:
  113. case Builtin::BI__builtin_isless:
  114. case Builtin::BI__builtin_islessequal:
  115. case Builtin::BI__builtin_islessgreater:
  116. case Builtin::BI__builtin_isunordered:
  117. if (SemaBuiltinUnorderedCompare(TheCall))
  118. return ExprError();
  119. break;
  120. case Builtin::BI__builtin_fpclassify:
  121. if (SemaBuiltinFPClassification(TheCall, 6))
  122. return ExprError();
  123. break;
  124. case Builtin::BI__builtin_isfinite:
  125. case Builtin::BI__builtin_isinf:
  126. case Builtin::BI__builtin_isinf_sign:
  127. case Builtin::BI__builtin_isnan:
  128. case Builtin::BI__builtin_isnormal:
  129. if (SemaBuiltinFPClassification(TheCall, 1))
  130. return ExprError();
  131. break;
  132. case Builtin::BI__builtin_shufflevector:
  133. return SemaBuiltinShuffleVector(TheCall);
  134. // TheCall will be freed by the smart pointer here, but that's fine, since
  135. // SemaBuiltinShuffleVector guts it, but then doesn't release it.
  136. case Builtin::BI__builtin_prefetch:
  137. if (SemaBuiltinPrefetch(TheCall))
  138. return ExprError();
  139. break;
  140. case Builtin::BI__builtin_object_size:
  141. if (SemaBuiltinObjectSize(TheCall))
  142. return ExprError();
  143. break;
  144. case Builtin::BI__builtin_longjmp:
  145. if (SemaBuiltinLongjmp(TheCall))
  146. return ExprError();
  147. break;
  148. case Builtin::BI__builtin_classify_type:
  149. if (checkArgCount(*this, TheCall, 1)) return true;
  150. TheCall->setType(Context.IntTy);
  151. break;
  152. case Builtin::BI__builtin_constant_p:
  153. if (checkArgCount(*this, TheCall, 1)) return true;
  154. TheCall->setType(Context.IntTy);
  155. break;
  156. case Builtin::BI__sync_fetch_and_add:
  157. case Builtin::BI__sync_fetch_and_sub:
  158. case Builtin::BI__sync_fetch_and_or:
  159. case Builtin::BI__sync_fetch_and_and:
  160. case Builtin::BI__sync_fetch_and_xor:
  161. case Builtin::BI__sync_add_and_fetch:
  162. case Builtin::BI__sync_sub_and_fetch:
  163. case Builtin::BI__sync_and_and_fetch:
  164. case Builtin::BI__sync_or_and_fetch:
  165. case Builtin::BI__sync_xor_and_fetch:
  166. case Builtin::BI__sync_val_compare_and_swap:
  167. case Builtin::BI__sync_bool_compare_and_swap:
  168. case Builtin::BI__sync_lock_test_and_set:
  169. case Builtin::BI__sync_lock_release:
  170. case Builtin::BI__sync_swap:
  171. return SemaBuiltinAtomicOverloaded(move(TheCallResult));
  172. }
  173. // Since the target specific builtins for each arch overlap, only check those
  174. // of the arch we are compiling for.
  175. if (BuiltinID >= Builtin::FirstTSBuiltin) {
  176. switch (Context.Target.getTriple().getArch()) {
  177. case llvm::Triple::arm:
  178. case llvm::Triple::thumb:
  179. if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
  180. return ExprError();
  181. break;
  182. default:
  183. break;
  184. }
  185. }
  186. return move(TheCallResult);
  187. }
  188. // Get the valid immediate range for the specified NEON type code.
  189. static unsigned RFT(unsigned t, bool shift = false) {
  190. bool quad = t & 0x10;
  191. switch (t & 0x7) {
  192. case 0: // i8
  193. return shift ? 7 : (8 << (int)quad) - 1;
  194. case 1: // i16
  195. return shift ? 15 : (4 << (int)quad) - 1;
  196. case 2: // i32
  197. return shift ? 31 : (2 << (int)quad) - 1;
  198. case 3: // i64
  199. return shift ? 63 : (1 << (int)quad) - 1;
  200. case 4: // f32
  201. assert(!shift && "cannot shift float types!");
  202. return (2 << (int)quad) - 1;
  203. case 5: // poly8
  204. return shift ? 7 : (8 << (int)quad) - 1;
  205. case 6: // poly16
  206. return shift ? 15 : (4 << (int)quad) - 1;
  207. case 7: // float16
  208. assert(!shift && "cannot shift float types!");
  209. return (4 << (int)quad) - 1;
  210. }
  211. return 0;
  212. }
  213. bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
  214. llvm::APSInt Result;
  215. unsigned mask = 0;
  216. unsigned TV = 0;
  217. switch (BuiltinID) {
  218. #define GET_NEON_OVERLOAD_CHECK
  219. #include "clang/Basic/arm_neon.inc"
  220. #undef GET_NEON_OVERLOAD_CHECK
  221. }
  222. // For NEON intrinsics which are overloaded on vector element type, validate
  223. // the immediate which specifies which variant to emit.
  224. if (mask) {
  225. unsigned ArgNo = TheCall->getNumArgs()-1;
  226. if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
  227. return true;
  228. TV = Result.getLimitedValue(32);
  229. if ((TV > 31) || (mask & (1 << TV)) == 0)
  230. return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
  231. << TheCall->getArg(ArgNo)->getSourceRange();
  232. }
  233. // For NEON intrinsics which take an immediate value as part of the
  234. // instruction, range check them here.
  235. unsigned i = 0, l = 0, u = 0;
  236. switch (BuiltinID) {
  237. default: return false;
  238. case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
  239. case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
  240. case ARM::BI__builtin_arm_vcvtr_f:
  241. case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
  242. #define GET_NEON_IMMEDIATE_CHECK
  243. #include "clang/Basic/arm_neon.inc"
  244. #undef GET_NEON_IMMEDIATE_CHECK
  245. };
  246. // Check that the immediate argument is actually a constant.
  247. if (SemaBuiltinConstantArg(TheCall, i, Result))
  248. return true;
  249. // Range check against the upper/lower values for this isntruction.
  250. unsigned Val = Result.getZExtValue();
  251. if (Val < l || Val > (u + l))
  252. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  253. << l << u+l << TheCall->getArg(i)->getSourceRange();
  254. // FIXME: VFP Intrinsics should error if VFP not present.
  255. return false;
  256. }
  257. /// CheckFunctionCall - Check a direct function call for various correctness
  258. /// and safety properties not strictly enforced by the C type system.
  259. bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
  260. // Get the IdentifierInfo* for the called function.
  261. IdentifierInfo *FnInfo = FDecl->getIdentifier();
  262. // None of the checks below are needed for functions that don't have
  263. // simple names (e.g., C++ conversion functions).
  264. if (!FnInfo)
  265. return false;
  266. // FIXME: This mechanism should be abstracted to be less fragile and
  267. // more efficient. For example, just map function ids to custom
  268. // handlers.
  269. // Printf and scanf checking.
  270. for (specific_attr_iterator<FormatAttr>
  271. i = FDecl->specific_attr_begin<FormatAttr>(),
  272. e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
  273. const FormatAttr *Format = *i;
  274. const bool b = Format->getType() == "scanf";
  275. if (b || CheckablePrintfAttr(Format, TheCall)) {
  276. bool HasVAListArg = Format->getFirstArg() == 0;
  277. CheckPrintfScanfArguments(TheCall, HasVAListArg,
  278. Format->getFormatIdx() - 1,
  279. HasVAListArg ? 0 : Format->getFirstArg() - 1,
  280. !b);
  281. }
  282. }
  283. for (specific_attr_iterator<NonNullAttr>
  284. i = FDecl->specific_attr_begin<NonNullAttr>(),
  285. e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
  286. CheckNonNullArguments(*i, TheCall->getArgs(),
  287. TheCall->getCallee()->getLocStart());
  288. }
  289. // Memset/memcpy/memmove handling
  290. if (FDecl->getLinkage() == ExternalLinkage &&
  291. (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
  292. if (FnInfo->isStr("memset") || FnInfo->isStr("memcpy") ||
  293. FnInfo->isStr("memmove"))
  294. CheckMemsetcpymoveArguments(TheCall, FnInfo);
  295. }
  296. return false;
  297. }
  298. bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
  299. // Printf checking.
  300. const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
  301. if (!Format)
  302. return false;
  303. const VarDecl *V = dyn_cast<VarDecl>(NDecl);
  304. if (!V)
  305. return false;
  306. QualType Ty = V->getType();
  307. if (!Ty->isBlockPointerType())
  308. return false;
  309. const bool b = Format->getType() == "scanf";
  310. if (!b && !CheckablePrintfAttr(Format, TheCall))
  311. return false;
  312. bool HasVAListArg = Format->getFirstArg() == 0;
  313. CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
  314. HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
  315. return false;
  316. }
  317. /// SemaBuiltinAtomicOverloaded - We have a call to a function like
  318. /// __sync_fetch_and_add, which is an overloaded function based on the pointer
  319. /// type of its first argument. The main ActOnCallExpr routines have already
  320. /// promoted the types of arguments because all of these calls are prototyped as
  321. /// void(...).
  322. ///
  323. /// This function goes through and does final semantic checking for these
  324. /// builtins,
  325. ExprResult
  326. Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
  327. CallExpr *TheCall = (CallExpr *)TheCallResult.get();
  328. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  329. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  330. // Ensure that we have at least one argument to do type inference from.
  331. if (TheCall->getNumArgs() < 1) {
  332. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  333. << 0 << 1 << TheCall->getNumArgs()
  334. << TheCall->getCallee()->getSourceRange();
  335. return ExprError();
  336. }
  337. // Inspect the first argument of the atomic builtin. This should always be
  338. // a pointer type, whose element is an integral scalar or pointer type.
  339. // Because it is a pointer type, we don't have to worry about any implicit
  340. // casts here.
  341. // FIXME: We don't allow floating point scalars as input.
  342. Expr *FirstArg = TheCall->getArg(0);
  343. const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
  344. if (!pointerType) {
  345. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
  346. << FirstArg->getType() << FirstArg->getSourceRange();
  347. return ExprError();
  348. }
  349. QualType ValType = pointerType->getPointeeType();
  350. if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
  351. !ValType->isBlockPointerType()) {
  352. Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
  353. << FirstArg->getType() << FirstArg->getSourceRange();
  354. return ExprError();
  355. }
  356. switch (ValType.getObjCLifetime()) {
  357. case Qualifiers::OCL_None:
  358. case Qualifiers::OCL_ExplicitNone:
  359. // okay
  360. break;
  361. case Qualifiers::OCL_Weak:
  362. case Qualifiers::OCL_Strong:
  363. case Qualifiers::OCL_Autoreleasing:
  364. Diag(DRE->getLocStart(), diag::err_arc_atomic_lifetime)
  365. << ValType << FirstArg->getSourceRange();
  366. return ExprError();
  367. }
  368. // The majority of builtins return a value, but a few have special return
  369. // types, so allow them to override appropriately below.
  370. QualType ResultType = ValType;
  371. // We need to figure out which concrete builtin this maps onto. For example,
  372. // __sync_fetch_and_add with a 2 byte object turns into
  373. // __sync_fetch_and_add_2.
  374. #define BUILTIN_ROW(x) \
  375. { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
  376. Builtin::BI##x##_8, Builtin::BI##x##_16 }
  377. static const unsigned BuiltinIndices[][5] = {
  378. BUILTIN_ROW(__sync_fetch_and_add),
  379. BUILTIN_ROW(__sync_fetch_and_sub),
  380. BUILTIN_ROW(__sync_fetch_and_or),
  381. BUILTIN_ROW(__sync_fetch_and_and),
  382. BUILTIN_ROW(__sync_fetch_and_xor),
  383. BUILTIN_ROW(__sync_add_and_fetch),
  384. BUILTIN_ROW(__sync_sub_and_fetch),
  385. BUILTIN_ROW(__sync_and_and_fetch),
  386. BUILTIN_ROW(__sync_or_and_fetch),
  387. BUILTIN_ROW(__sync_xor_and_fetch),
  388. BUILTIN_ROW(__sync_val_compare_and_swap),
  389. BUILTIN_ROW(__sync_bool_compare_and_swap),
  390. BUILTIN_ROW(__sync_lock_test_and_set),
  391. BUILTIN_ROW(__sync_lock_release),
  392. BUILTIN_ROW(__sync_swap)
  393. };
  394. #undef BUILTIN_ROW
  395. // Determine the index of the size.
  396. unsigned SizeIndex;
  397. switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
  398. case 1: SizeIndex = 0; break;
  399. case 2: SizeIndex = 1; break;
  400. case 4: SizeIndex = 2; break;
  401. case 8: SizeIndex = 3; break;
  402. case 16: SizeIndex = 4; break;
  403. default:
  404. Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
  405. << FirstArg->getType() << FirstArg->getSourceRange();
  406. return ExprError();
  407. }
  408. // Each of these builtins has one pointer argument, followed by some number of
  409. // values (0, 1 or 2) followed by a potentially empty varags list of stuff
  410. // that we ignore. Find out which row of BuiltinIndices to read from as well
  411. // as the number of fixed args.
  412. unsigned BuiltinID = FDecl->getBuiltinID();
  413. unsigned BuiltinIndex, NumFixed = 1;
  414. switch (BuiltinID) {
  415. default: assert(0 && "Unknown overloaded atomic builtin!");
  416. case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
  417. case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
  418. case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
  419. case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
  420. case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
  421. case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
  422. case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
  423. case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
  424. case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
  425. case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
  426. case Builtin::BI__sync_val_compare_and_swap:
  427. BuiltinIndex = 10;
  428. NumFixed = 2;
  429. break;
  430. case Builtin::BI__sync_bool_compare_and_swap:
  431. BuiltinIndex = 11;
  432. NumFixed = 2;
  433. ResultType = Context.BoolTy;
  434. break;
  435. case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
  436. case Builtin::BI__sync_lock_release:
  437. BuiltinIndex = 13;
  438. NumFixed = 0;
  439. ResultType = Context.VoidTy;
  440. break;
  441. case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
  442. }
  443. // Now that we know how many fixed arguments we expect, first check that we
  444. // have at least that many.
  445. if (TheCall->getNumArgs() < 1+NumFixed) {
  446. Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
  447. << 0 << 1+NumFixed << TheCall->getNumArgs()
  448. << TheCall->getCallee()->getSourceRange();
  449. return ExprError();
  450. }
  451. // Get the decl for the concrete builtin from this, we can tell what the
  452. // concrete integer type we should convert to is.
  453. unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
  454. const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
  455. IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
  456. FunctionDecl *NewBuiltinDecl =
  457. cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
  458. TUScope, false, DRE->getLocStart()));
  459. // The first argument --- the pointer --- has a fixed type; we
  460. // deduce the types of the rest of the arguments accordingly. Walk
  461. // the remaining arguments, converting them to the deduced value type.
  462. for (unsigned i = 0; i != NumFixed; ++i) {
  463. ExprResult Arg = TheCall->getArg(i+1);
  464. // If the argument is an implicit cast, then there was a promotion due to
  465. // "...", just remove it now.
  466. if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
  467. Arg = ICE->getSubExpr();
  468. ICE->setSubExpr(0);
  469. TheCall->setArg(i+1, Arg.get());
  470. }
  471. // GCC does an implicit conversion to the pointer or integer ValType. This
  472. // can fail in some cases (1i -> int**), check for this error case now.
  473. CastKind Kind = CK_Invalid;
  474. ExprValueKind VK = VK_RValue;
  475. CXXCastPath BasePath;
  476. Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(),
  477. ValType, Arg.take(), Kind, VK, BasePath);
  478. if (Arg.isInvalid())
  479. return ExprError();
  480. // Okay, we have something that *can* be converted to the right type. Check
  481. // to see if there is a potentially weird extension going on here. This can
  482. // happen when you do an atomic operation on something like an char* and
  483. // pass in 42. The 42 gets converted to char. This is even more strange
  484. // for things like 45.123 -> char, etc.
  485. // FIXME: Do this check.
  486. Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
  487. TheCall->setArg(i+1, Arg.get());
  488. }
  489. // Switch the DeclRefExpr to refer to the new decl.
  490. DRE->setDecl(NewBuiltinDecl);
  491. DRE->setType(NewBuiltinDecl->getType());
  492. // Set the callee in the CallExpr.
  493. // FIXME: This leaks the original parens and implicit casts.
  494. ExprResult PromotedCall = UsualUnaryConversions(DRE);
  495. if (PromotedCall.isInvalid())
  496. return ExprError();
  497. TheCall->setCallee(PromotedCall.take());
  498. // Change the result type of the call to match the original value type. This
  499. // is arbitrary, but the codegen for these builtins ins design to handle it
  500. // gracefully.
  501. TheCall->setType(ResultType);
  502. return move(TheCallResult);
  503. }
  504. /// CheckObjCString - Checks that the argument to the builtin
  505. /// CFString constructor is correct
  506. /// Note: It might also make sense to do the UTF-16 conversion here (would
  507. /// simplify the backend).
  508. bool Sema::CheckObjCString(Expr *Arg) {
  509. Arg = Arg->IgnoreParenCasts();
  510. StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
  511. if (!Literal || Literal->isWide()) {
  512. Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
  513. << Arg->getSourceRange();
  514. return true;
  515. }
  516. if (Literal->containsNonAsciiOrNull()) {
  517. llvm::StringRef String = Literal->getString();
  518. unsigned NumBytes = String.size();
  519. llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
  520. const UTF8 *FromPtr = (UTF8 *)String.data();
  521. UTF16 *ToPtr = &ToBuf[0];
  522. ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
  523. &ToPtr, ToPtr + NumBytes,
  524. strictConversion);
  525. // Check for conversion failure.
  526. if (Result != conversionOK)
  527. Diag(Arg->getLocStart(),
  528. diag::warn_cfstring_truncated) << Arg->getSourceRange();
  529. }
  530. return false;
  531. }
  532. /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
  533. /// Emit an error and return true on failure, return false on success.
  534. bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
  535. Expr *Fn = TheCall->getCallee();
  536. if (TheCall->getNumArgs() > 2) {
  537. Diag(TheCall->getArg(2)->getLocStart(),
  538. diag::err_typecheck_call_too_many_args)
  539. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  540. << Fn->getSourceRange()
  541. << SourceRange(TheCall->getArg(2)->getLocStart(),
  542. (*(TheCall->arg_end()-1))->getLocEnd());
  543. return true;
  544. }
  545. if (TheCall->getNumArgs() < 2) {
  546. return Diag(TheCall->getLocEnd(),
  547. diag::err_typecheck_call_too_few_args_at_least)
  548. << 0 /*function call*/ << 2 << TheCall->getNumArgs();
  549. }
  550. // Determine whether the current function is variadic or not.
  551. BlockScopeInfo *CurBlock = getCurBlock();
  552. bool isVariadic;
  553. if (CurBlock)
  554. isVariadic = CurBlock->TheDecl->isVariadic();
  555. else if (FunctionDecl *FD = getCurFunctionDecl())
  556. isVariadic = FD->isVariadic();
  557. else
  558. isVariadic = getCurMethodDecl()->isVariadic();
  559. if (!isVariadic) {
  560. Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
  561. return true;
  562. }
  563. // Verify that the second argument to the builtin is the last argument of the
  564. // current function or method.
  565. bool SecondArgIsLastNamedArgument = false;
  566. const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
  567. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
  568. if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
  569. // FIXME: This isn't correct for methods (results in bogus warning).
  570. // Get the last formal in the current function.
  571. const ParmVarDecl *LastArg;
  572. if (CurBlock)
  573. LastArg = *(CurBlock->TheDecl->param_end()-1);
  574. else if (FunctionDecl *FD = getCurFunctionDecl())
  575. LastArg = *(FD->param_end()-1);
  576. else
  577. LastArg = *(getCurMethodDecl()->param_end()-1);
  578. SecondArgIsLastNamedArgument = PV == LastArg;
  579. }
  580. }
  581. if (!SecondArgIsLastNamedArgument)
  582. Diag(TheCall->getArg(1)->getLocStart(),
  583. diag::warn_second_parameter_of_va_start_not_last_named_argument);
  584. return false;
  585. }
  586. /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
  587. /// friends. This is declared to take (...), so we have to check everything.
  588. bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
  589. if (TheCall->getNumArgs() < 2)
  590. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  591. << 0 << 2 << TheCall->getNumArgs()/*function call*/;
  592. if (TheCall->getNumArgs() > 2)
  593. return Diag(TheCall->getArg(2)->getLocStart(),
  594. diag::err_typecheck_call_too_many_args)
  595. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  596. << SourceRange(TheCall->getArg(2)->getLocStart(),
  597. (*(TheCall->arg_end()-1))->getLocEnd());
  598. ExprResult OrigArg0 = TheCall->getArg(0);
  599. ExprResult OrigArg1 = TheCall->getArg(1);
  600. // Do standard promotions between the two arguments, returning their common
  601. // type.
  602. QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
  603. if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
  604. return true;
  605. // Make sure any conversions are pushed back into the call; this is
  606. // type safe since unordered compare builtins are declared as "_Bool
  607. // foo(...)".
  608. TheCall->setArg(0, OrigArg0.get());
  609. TheCall->setArg(1, OrigArg1.get());
  610. if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
  611. return false;
  612. // If the common type isn't a real floating type, then the arguments were
  613. // invalid for this operation.
  614. if (!Res->isRealFloatingType())
  615. return Diag(OrigArg0.get()->getLocStart(),
  616. diag::err_typecheck_call_invalid_ordered_compare)
  617. << OrigArg0.get()->getType() << OrigArg1.get()->getType()
  618. << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
  619. return false;
  620. }
  621. /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
  622. /// __builtin_isnan and friends. This is declared to take (...), so we have
  623. /// to check everything. We expect the last argument to be a floating point
  624. /// value.
  625. bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
  626. if (TheCall->getNumArgs() < NumArgs)
  627. return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
  628. << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
  629. if (TheCall->getNumArgs() > NumArgs)
  630. return Diag(TheCall->getArg(NumArgs)->getLocStart(),
  631. diag::err_typecheck_call_too_many_args)
  632. << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
  633. << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
  634. (*(TheCall->arg_end()-1))->getLocEnd());
  635. Expr *OrigArg = TheCall->getArg(NumArgs-1);
  636. if (OrigArg->isTypeDependent())
  637. return false;
  638. // This operation requires a non-_Complex floating-point number.
  639. if (!OrigArg->getType()->isRealFloatingType())
  640. return Diag(OrigArg->getLocStart(),
  641. diag::err_typecheck_call_invalid_unary_fp)
  642. << OrigArg->getType() << OrigArg->getSourceRange();
  643. // If this is an implicit conversion from float -> double, remove it.
  644. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
  645. Expr *CastArg = Cast->getSubExpr();
  646. if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
  647. assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
  648. "promotion from float to double is the only expected cast here");
  649. Cast->setSubExpr(0);
  650. TheCall->setArg(NumArgs-1, CastArg);
  651. OrigArg = CastArg;
  652. }
  653. }
  654. return false;
  655. }
  656. /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
  657. // This is declared to take (...), so we have to check everything.
  658. ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
  659. if (TheCall->getNumArgs() < 2)
  660. return ExprError(Diag(TheCall->getLocEnd(),
  661. diag::err_typecheck_call_too_few_args_at_least)
  662. << 0 /*function call*/ << 2 << TheCall->getNumArgs()
  663. << TheCall->getSourceRange());
  664. // Determine which of the following types of shufflevector we're checking:
  665. // 1) unary, vector mask: (lhs, mask)
  666. // 2) binary, vector mask: (lhs, rhs, mask)
  667. // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
  668. QualType resType = TheCall->getArg(0)->getType();
  669. unsigned numElements = 0;
  670. if (!TheCall->getArg(0)->isTypeDependent() &&
  671. !TheCall->getArg(1)->isTypeDependent()) {
  672. QualType LHSType = TheCall->getArg(0)->getType();
  673. QualType RHSType = TheCall->getArg(1)->getType();
  674. if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
  675. Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
  676. << SourceRange(TheCall->getArg(0)->getLocStart(),
  677. TheCall->getArg(1)->getLocEnd());
  678. return ExprError();
  679. }
  680. numElements = LHSType->getAs<VectorType>()->getNumElements();
  681. unsigned numResElements = TheCall->getNumArgs() - 2;
  682. // Check to see if we have a call with 2 vector arguments, the unary shuffle
  683. // with mask. If so, verify that RHS is an integer vector type with the
  684. // same number of elts as lhs.
  685. if (TheCall->getNumArgs() == 2) {
  686. if (!RHSType->hasIntegerRepresentation() ||
  687. RHSType->getAs<VectorType>()->getNumElements() != numElements)
  688. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  689. << SourceRange(TheCall->getArg(1)->getLocStart(),
  690. TheCall->getArg(1)->getLocEnd());
  691. numResElements = numElements;
  692. }
  693. else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
  694. Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
  695. << SourceRange(TheCall->getArg(0)->getLocStart(),
  696. TheCall->getArg(1)->getLocEnd());
  697. return ExprError();
  698. } else if (numElements != numResElements) {
  699. QualType eltType = LHSType->getAs<VectorType>()->getElementType();
  700. resType = Context.getVectorType(eltType, numResElements,
  701. VectorType::GenericVector);
  702. }
  703. }
  704. for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
  705. if (TheCall->getArg(i)->isTypeDependent() ||
  706. TheCall->getArg(i)->isValueDependent())
  707. continue;
  708. llvm::APSInt Result(32);
  709. if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
  710. return ExprError(Diag(TheCall->getLocStart(),
  711. diag::err_shufflevector_nonconstant_argument)
  712. << TheCall->getArg(i)->getSourceRange());
  713. if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
  714. return ExprError(Diag(TheCall->getLocStart(),
  715. diag::err_shufflevector_argument_too_large)
  716. << TheCall->getArg(i)->getSourceRange());
  717. }
  718. llvm::SmallVector<Expr*, 32> exprs;
  719. for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
  720. exprs.push_back(TheCall->getArg(i));
  721. TheCall->setArg(i, 0);
  722. }
  723. return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
  724. exprs.size(), resType,
  725. TheCall->getCallee()->getLocStart(),
  726. TheCall->getRParenLoc()));
  727. }
  728. /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
  729. // This is declared to take (const void*, ...) and can take two
  730. // optional constant int args.
  731. bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
  732. unsigned NumArgs = TheCall->getNumArgs();
  733. if (NumArgs > 3)
  734. return Diag(TheCall->getLocEnd(),
  735. diag::err_typecheck_call_too_many_args_at_most)
  736. << 0 /*function call*/ << 3 << NumArgs
  737. << TheCall->getSourceRange();
  738. // Argument 0 is checked for us and the remaining arguments must be
  739. // constant integers.
  740. for (unsigned i = 1; i != NumArgs; ++i) {
  741. Expr *Arg = TheCall->getArg(i);
  742. llvm::APSInt Result;
  743. if (SemaBuiltinConstantArg(TheCall, i, Result))
  744. return true;
  745. // FIXME: gcc issues a warning and rewrites these to 0. These
  746. // seems especially odd for the third argument since the default
  747. // is 3.
  748. if (i == 1) {
  749. if (Result.getLimitedValue() > 1)
  750. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  751. << "0" << "1" << Arg->getSourceRange();
  752. } else {
  753. if (Result.getLimitedValue() > 3)
  754. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  755. << "0" << "3" << Arg->getSourceRange();
  756. }
  757. }
  758. return false;
  759. }
  760. /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
  761. /// TheCall is a constant expression.
  762. bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
  763. llvm::APSInt &Result) {
  764. Expr *Arg = TheCall->getArg(ArgNum);
  765. DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
  766. FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
  767. if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
  768. if (!Arg->isIntegerConstantExpr(Result, Context))
  769. return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
  770. << FDecl->getDeclName() << Arg->getSourceRange();
  771. return false;
  772. }
  773. /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
  774. /// int type). This simply type checks that type is one of the defined
  775. /// constants (0-3).
  776. // For compatibility check 0-3, llvm only handles 0 and 2.
  777. bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
  778. llvm::APSInt Result;
  779. // Check constant-ness first.
  780. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  781. return true;
  782. Expr *Arg = TheCall->getArg(1);
  783. if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
  784. return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
  785. << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  786. }
  787. return false;
  788. }
  789. /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
  790. /// This checks that val is a constant 1.
  791. bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
  792. Expr *Arg = TheCall->getArg(1);
  793. llvm::APSInt Result;
  794. // TODO: This is less than ideal. Overload this to take a value.
  795. if (SemaBuiltinConstantArg(TheCall, 1, Result))
  796. return true;
  797. if (Result != 1)
  798. return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
  799. << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
  800. return false;
  801. }
  802. // Handle i > 1 ? "x" : "y", recursively.
  803. bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
  804. bool HasVAListArg,
  805. unsigned format_idx, unsigned firstDataArg,
  806. bool isPrintf) {
  807. tryAgain:
  808. if (E->isTypeDependent() || E->isValueDependent())
  809. return false;
  810. E = E->IgnoreParens();
  811. switch (E->getStmtClass()) {
  812. case Stmt::BinaryConditionalOperatorClass:
  813. case Stmt::ConditionalOperatorClass: {
  814. const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
  815. return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
  816. format_idx, firstDataArg, isPrintf)
  817. && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
  818. format_idx, firstDataArg, isPrintf);
  819. }
  820. case Stmt::IntegerLiteralClass:
  821. // Technically -Wformat-nonliteral does not warn about this case.
  822. // The behavior of printf and friends in this case is implementation
  823. // dependent. Ideally if the format string cannot be null then
  824. // it should have a 'nonnull' attribute in the function prototype.
  825. return true;
  826. case Stmt::ImplicitCastExprClass: {
  827. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  828. goto tryAgain;
  829. }
  830. case Stmt::OpaqueValueExprClass:
  831. if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
  832. E = src;
  833. goto tryAgain;
  834. }
  835. return false;
  836. case Stmt::PredefinedExprClass:
  837. // While __func__, etc., are technically not string literals, they
  838. // cannot contain format specifiers and thus are not a security
  839. // liability.
  840. return true;
  841. case Stmt::DeclRefExprClass: {
  842. const DeclRefExpr *DR = cast<DeclRefExpr>(E);
  843. // As an exception, do not flag errors for variables binding to
  844. // const string literals.
  845. if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  846. bool isConstant = false;
  847. QualType T = DR->getType();
  848. if (const ArrayType *AT = Context.getAsArrayType(T)) {
  849. isConstant = AT->getElementType().isConstant(Context);
  850. } else if (const PointerType *PT = T->getAs<PointerType>()) {
  851. isConstant = T.isConstant(Context) &&
  852. PT->getPointeeType().isConstant(Context);
  853. }
  854. if (isConstant) {
  855. if (const Expr *Init = VD->getAnyInitializer())
  856. return SemaCheckStringLiteral(Init, TheCall,
  857. HasVAListArg, format_idx, firstDataArg,
  858. isPrintf);
  859. }
  860. // For vprintf* functions (i.e., HasVAListArg==true), we add a
  861. // special check to see if the format string is a function parameter
  862. // of the function calling the printf function. If the function
  863. // has an attribute indicating it is a printf-like function, then we
  864. // should suppress warnings concerning non-literals being used in a call
  865. // to a vprintf function. For example:
  866. //
  867. // void
  868. // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
  869. // va_list ap;
  870. // va_start(ap, fmt);
  871. // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
  872. // ...
  873. //
  874. //
  875. // FIXME: We don't have full attribute support yet, so just check to see
  876. // if the argument is a DeclRefExpr that references a parameter. We'll
  877. // add proper support for checking the attribute later.
  878. if (HasVAListArg)
  879. if (isa<ParmVarDecl>(VD))
  880. return true;
  881. }
  882. return false;
  883. }
  884. case Stmt::CallExprClass: {
  885. const CallExpr *CE = cast<CallExpr>(E);
  886. if (const ImplicitCastExpr *ICE
  887. = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
  888. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
  889. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
  890. if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
  891. unsigned ArgIndex = FA->getFormatIdx();
  892. const Expr *Arg = CE->getArg(ArgIndex - 1);
  893. return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
  894. format_idx, firstDataArg, isPrintf);
  895. }
  896. }
  897. }
  898. }
  899. return false;
  900. }
  901. case Stmt::ObjCStringLiteralClass:
  902. case Stmt::StringLiteralClass: {
  903. const StringLiteral *StrE = NULL;
  904. if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
  905. StrE = ObjCFExpr->getString();
  906. else
  907. StrE = cast<StringLiteral>(E);
  908. if (StrE) {
  909. CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
  910. firstDataArg, isPrintf);
  911. return true;
  912. }
  913. return false;
  914. }
  915. default:
  916. return false;
  917. }
  918. }
  919. void
  920. Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
  921. const Expr * const *ExprArgs,
  922. SourceLocation CallSiteLoc) {
  923. for (NonNullAttr::args_iterator i = NonNull->args_begin(),
  924. e = NonNull->args_end();
  925. i != e; ++i) {
  926. const Expr *ArgExpr = ExprArgs[*i];
  927. if (ArgExpr->isNullPointerConstant(Context,
  928. Expr::NPC_ValueDependentIsNotNull))
  929. Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
  930. }
  931. }
  932. /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
  933. /// functions) for correct use of format strings.
  934. void
  935. Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
  936. unsigned format_idx, unsigned firstDataArg,
  937. bool isPrintf) {
  938. const Expr *Fn = TheCall->getCallee();
  939. // The way the format attribute works in GCC, the implicit this argument
  940. // of member functions is counted. However, it doesn't appear in our own
  941. // lists, so decrement format_idx in that case.
  942. if (isa<CXXMemberCallExpr>(TheCall)) {
  943. const CXXMethodDecl *method_decl =
  944. dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
  945. if (method_decl && method_decl->isInstance()) {
  946. // Catch a format attribute mistakenly referring to the object argument.
  947. if (format_idx == 0)
  948. return;
  949. --format_idx;
  950. if(firstDataArg != 0)
  951. --firstDataArg;
  952. }
  953. }
  954. // CHECK: printf/scanf-like function is called with no format string.
  955. if (format_idx >= TheCall->getNumArgs()) {
  956. Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
  957. << Fn->getSourceRange();
  958. return;
  959. }
  960. const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
  961. // CHECK: format string is not a string literal.
  962. //
  963. // Dynamically generated format strings are difficult to
  964. // automatically vet at compile time. Requiring that format strings
  965. // are string literals: (1) permits the checking of format strings by
  966. // the compiler and thereby (2) can practically remove the source of
  967. // many format string exploits.
  968. // Format string can be either ObjC string (e.g. @"%d") or
  969. // C string (e.g. "%d")
  970. // ObjC string uses the same format specifiers as C string, so we can use
  971. // the same format string checking logic for both ObjC and C strings.
  972. if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
  973. firstDataArg, isPrintf))
  974. return; // Literal format string found, check done!
  975. // If there are no arguments specified, warn with -Wformat-security, otherwise
  976. // warn only with -Wformat-nonliteral.
  977. if (TheCall->getNumArgs() == format_idx+1)
  978. Diag(TheCall->getArg(format_idx)->getLocStart(),
  979. diag::warn_format_nonliteral_noargs)
  980. << OrigFormatExpr->getSourceRange();
  981. else
  982. Diag(TheCall->getArg(format_idx)->getLocStart(),
  983. diag::warn_format_nonliteral)
  984. << OrigFormatExpr->getSourceRange();
  985. }
  986. namespace {
  987. class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
  988. protected:
  989. Sema &S;
  990. const StringLiteral *FExpr;
  991. const Expr *OrigFormatExpr;
  992. const unsigned FirstDataArg;
  993. const unsigned NumDataArgs;
  994. const bool IsObjCLiteral;
  995. const char *Beg; // Start of format string.
  996. const bool HasVAListArg;
  997. const CallExpr *TheCall;
  998. unsigned FormatIdx;
  999. llvm::BitVector CoveredArgs;
  1000. bool usesPositionalArgs;
  1001. bool atFirstArg;
  1002. public:
  1003. CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
  1004. const Expr *origFormatExpr, unsigned firstDataArg,
  1005. unsigned numDataArgs, bool isObjCLiteral,
  1006. const char *beg, bool hasVAListArg,
  1007. const CallExpr *theCall, unsigned formatIdx)
  1008. : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
  1009. FirstDataArg(firstDataArg),
  1010. NumDataArgs(numDataArgs),
  1011. IsObjCLiteral(isObjCLiteral), Beg(beg),
  1012. HasVAListArg(hasVAListArg),
  1013. TheCall(theCall), FormatIdx(formatIdx),
  1014. usesPositionalArgs(false), atFirstArg(true) {
  1015. CoveredArgs.resize(numDataArgs);
  1016. CoveredArgs.reset();
  1017. }
  1018. void DoneProcessing();
  1019. void HandleIncompleteSpecifier(const char *startSpecifier,
  1020. unsigned specifierLen);
  1021. virtual void HandleInvalidPosition(const char *startSpecifier,
  1022. unsigned specifierLen,
  1023. analyze_format_string::PositionContext p);
  1024. virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
  1025. void HandleNullChar(const char *nullCharacter);
  1026. protected:
  1027. bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
  1028. const char *startSpec,
  1029. unsigned specifierLen,
  1030. const char *csStart, unsigned csLen);
  1031. SourceRange getFormatStringRange();
  1032. CharSourceRange getSpecifierRange(const char *startSpecifier,
  1033. unsigned specifierLen);
  1034. SourceLocation getLocationOfByte(const char *x);
  1035. const Expr *getDataArg(unsigned i) const;
  1036. bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
  1037. const analyze_format_string::ConversionSpecifier &CS,
  1038. const char *startSpecifier, unsigned specifierLen,
  1039. unsigned argIndex);
  1040. };
  1041. }
  1042. SourceRange CheckFormatHandler::getFormatStringRange() {
  1043. return OrigFormatExpr->getSourceRange();
  1044. }
  1045. CharSourceRange CheckFormatHandler::
  1046. getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
  1047. SourceLocation Start = getLocationOfByte(startSpecifier);
  1048. SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
  1049. // Advance the end SourceLocation by one due to half-open ranges.
  1050. End = End.getFileLocWithOffset(1);
  1051. return CharSourceRange::getCharRange(Start, End);
  1052. }
  1053. SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
  1054. return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
  1055. }
  1056. void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
  1057. unsigned specifierLen){
  1058. SourceLocation Loc = getLocationOfByte(startSpecifier);
  1059. S.Diag(Loc, diag::warn_printf_incomplete_specifier)
  1060. << getSpecifierRange(startSpecifier, specifierLen);
  1061. }
  1062. void
  1063. CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
  1064. analyze_format_string::PositionContext p) {
  1065. SourceLocation Loc = getLocationOfByte(startPos);
  1066. S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
  1067. << (unsigned) p << getSpecifierRange(startPos, posLen);
  1068. }
  1069. void CheckFormatHandler::HandleZeroPosition(const char *startPos,
  1070. unsigned posLen) {
  1071. SourceLocation Loc = getLocationOfByte(startPos);
  1072. S.Diag(Loc, diag::warn_format_zero_positional_specifier)
  1073. << getSpecifierRange(startPos, posLen);
  1074. }
  1075. void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
  1076. if (!IsObjCLiteral) {
  1077. // The presence of a null character is likely an error.
  1078. S.Diag(getLocationOfByte(nullCharacter),
  1079. diag::warn_printf_format_string_contains_null_char)
  1080. << getFormatStringRange();
  1081. }
  1082. }
  1083. const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
  1084. return TheCall->getArg(FirstDataArg + i);
  1085. }
  1086. void CheckFormatHandler::DoneProcessing() {
  1087. // Does the number of data arguments exceed the number of
  1088. // format conversions in the format string?
  1089. if (!HasVAListArg) {
  1090. // Find any arguments that weren't covered.
  1091. CoveredArgs.flip();
  1092. signed notCoveredArg = CoveredArgs.find_first();
  1093. if (notCoveredArg >= 0) {
  1094. assert((unsigned)notCoveredArg < NumDataArgs);
  1095. S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
  1096. diag::warn_printf_data_arg_not_used)
  1097. << getFormatStringRange();
  1098. }
  1099. }
  1100. }
  1101. bool
  1102. CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
  1103. SourceLocation Loc,
  1104. const char *startSpec,
  1105. unsigned specifierLen,
  1106. const char *csStart,
  1107. unsigned csLen) {
  1108. bool keepGoing = true;
  1109. if (argIndex < NumDataArgs) {
  1110. // Consider the argument coverered, even though the specifier doesn't
  1111. // make sense.
  1112. CoveredArgs.set(argIndex);
  1113. }
  1114. else {
  1115. // If argIndex exceeds the number of data arguments we
  1116. // don't issue a warning because that is just a cascade of warnings (and
  1117. // they may have intended '%%' anyway). We don't want to continue processing
  1118. // the format string after this point, however, as we will like just get
  1119. // gibberish when trying to match arguments.
  1120. keepGoing = false;
  1121. }
  1122. S.Diag(Loc, diag::warn_format_invalid_conversion)
  1123. << llvm::StringRef(csStart, csLen)
  1124. << getSpecifierRange(startSpec, specifierLen);
  1125. return keepGoing;
  1126. }
  1127. bool
  1128. CheckFormatHandler::CheckNumArgs(
  1129. const analyze_format_string::FormatSpecifier &FS,
  1130. const analyze_format_string::ConversionSpecifier &CS,
  1131. const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
  1132. if (argIndex >= NumDataArgs) {
  1133. if (FS.usesPositionalArg()) {
  1134. S.Diag(getLocationOfByte(CS.getStart()),
  1135. diag::warn_printf_positional_arg_exceeds_data_args)
  1136. << (argIndex+1) << NumDataArgs
  1137. << getSpecifierRange(startSpecifier, specifierLen);
  1138. }
  1139. else {
  1140. S.Diag(getLocationOfByte(CS.getStart()),
  1141. diag::warn_printf_insufficient_data_args)
  1142. << getSpecifierRange(startSpecifier, specifierLen);
  1143. }
  1144. return false;
  1145. }
  1146. return true;
  1147. }
  1148. //===--- CHECK: Printf format string checking ------------------------------===//
  1149. namespace {
  1150. class CheckPrintfHandler : public CheckFormatHandler {
  1151. public:
  1152. CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
  1153. const Expr *origFormatExpr, unsigned firstDataArg,
  1154. unsigned numDataArgs, bool isObjCLiteral,
  1155. const char *beg, bool hasVAListArg,
  1156. const CallExpr *theCall, unsigned formatIdx)
  1157. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  1158. numDataArgs, isObjCLiteral, beg, hasVAListArg,
  1159. theCall, formatIdx) {}
  1160. bool HandleInvalidPrintfConversionSpecifier(
  1161. const analyze_printf::PrintfSpecifier &FS,
  1162. const char *startSpecifier,
  1163. unsigned specifierLen);
  1164. bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
  1165. const char *startSpecifier,
  1166. unsigned specifierLen);
  1167. bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
  1168. const char *startSpecifier, unsigned specifierLen);
  1169. void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
  1170. const analyze_printf::OptionalAmount &Amt,
  1171. unsigned type,
  1172. const char *startSpecifier, unsigned specifierLen);
  1173. void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  1174. const analyze_printf::OptionalFlag &flag,
  1175. const char *startSpecifier, unsigned specifierLen);
  1176. void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
  1177. const analyze_printf::OptionalFlag &ignoredFlag,
  1178. const analyze_printf::OptionalFlag &flag,
  1179. const char *startSpecifier, unsigned specifierLen);
  1180. };
  1181. }
  1182. bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
  1183. const analyze_printf::PrintfSpecifier &FS,
  1184. const char *startSpecifier,
  1185. unsigned specifierLen) {
  1186. const analyze_printf::PrintfConversionSpecifier &CS =
  1187. FS.getConversionSpecifier();
  1188. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  1189. getLocationOfByte(CS.getStart()),
  1190. startSpecifier, specifierLen,
  1191. CS.getStart(), CS.getLength());
  1192. }
  1193. bool CheckPrintfHandler::HandleAmount(
  1194. const analyze_format_string::OptionalAmount &Amt,
  1195. unsigned k, const char *startSpecifier,
  1196. unsigned specifierLen) {
  1197. if (Amt.hasDataArgument()) {
  1198. if (!HasVAListArg) {
  1199. unsigned argIndex = Amt.getArgIndex();
  1200. if (argIndex >= NumDataArgs) {
  1201. S.Diag(getLocationOfByte(Amt.getStart()),
  1202. diag::warn_printf_asterisk_missing_arg)
  1203. << k << getSpecifierRange(startSpecifier, specifierLen);
  1204. // Don't do any more checking. We will just emit
  1205. // spurious errors.
  1206. return false;
  1207. }
  1208. // Type check the data argument. It should be an 'int'.
  1209. // Although not in conformance with C99, we also allow the argument to be
  1210. // an 'unsigned int' as that is a reasonably safe case. GCC also
  1211. // doesn't emit a warning for that case.
  1212. CoveredArgs.set(argIndex);
  1213. const Expr *Arg = getDataArg(argIndex);
  1214. QualType T = Arg->getType();
  1215. const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
  1216. assert(ATR.isValid());
  1217. if (!ATR.matchesType(S.Context, T)) {
  1218. S.Diag(getLocationOfByte(Amt.getStart()),
  1219. diag::warn_printf_asterisk_wrong_type)
  1220. << k
  1221. << ATR.getRepresentativeType(S.Context) << T
  1222. << getSpecifierRange(startSpecifier, specifierLen)
  1223. << Arg->getSourceRange();
  1224. // Don't do any more checking. We will just emit
  1225. // spurious errors.
  1226. return false;
  1227. }
  1228. }
  1229. }
  1230. return true;
  1231. }
  1232. void CheckPrintfHandler::HandleInvalidAmount(
  1233. const analyze_printf::PrintfSpecifier &FS,
  1234. const analyze_printf::OptionalAmount &Amt,
  1235. unsigned type,
  1236. const char *startSpecifier,
  1237. unsigned specifierLen) {
  1238. const analyze_printf::PrintfConversionSpecifier &CS =
  1239. FS.getConversionSpecifier();
  1240. switch (Amt.getHowSpecified()) {
  1241. case analyze_printf::OptionalAmount::Constant:
  1242. S.Diag(getLocationOfByte(Amt.getStart()),
  1243. diag::warn_printf_nonsensical_optional_amount)
  1244. << type
  1245. << CS.toString()
  1246. << getSpecifierRange(startSpecifier, specifierLen)
  1247. << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
  1248. Amt.getConstantLength()));
  1249. break;
  1250. default:
  1251. S.Diag(getLocationOfByte(Amt.getStart()),
  1252. diag::warn_printf_nonsensical_optional_amount)
  1253. << type
  1254. << CS.toString()
  1255. << getSpecifierRange(startSpecifier, specifierLen);
  1256. break;
  1257. }
  1258. }
  1259. void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
  1260. const analyze_printf::OptionalFlag &flag,
  1261. const char *startSpecifier,
  1262. unsigned specifierLen) {
  1263. // Warn about pointless flag with a fixit removal.
  1264. const analyze_printf::PrintfConversionSpecifier &CS =
  1265. FS.getConversionSpecifier();
  1266. S.Diag(getLocationOfByte(flag.getPosition()),
  1267. diag::warn_printf_nonsensical_flag)
  1268. << flag.toString() << CS.toString()
  1269. << getSpecifierRange(startSpecifier, specifierLen)
  1270. << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
  1271. }
  1272. void CheckPrintfHandler::HandleIgnoredFlag(
  1273. const analyze_printf::PrintfSpecifier &FS,
  1274. const analyze_printf::OptionalFlag &ignoredFlag,
  1275. const analyze_printf::OptionalFlag &flag,
  1276. const char *startSpecifier,
  1277. unsigned specifierLen) {
  1278. // Warn about ignored flag with a fixit removal.
  1279. S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
  1280. diag::warn_printf_ignored_flag)
  1281. << ignoredFlag.toString() << flag.toString()
  1282. << getSpecifierRange(startSpecifier, specifierLen)
  1283. << FixItHint::CreateRemoval(getSpecifierRange(
  1284. ignoredFlag.getPosition(), 1));
  1285. }
  1286. bool
  1287. CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
  1288. &FS,
  1289. const char *startSpecifier,
  1290. unsigned specifierLen) {
  1291. using namespace analyze_format_string;
  1292. using namespace analyze_printf;
  1293. const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
  1294. if (FS.consumesDataArgument()) {
  1295. if (atFirstArg) {
  1296. atFirstArg = false;
  1297. usesPositionalArgs = FS.usesPositionalArg();
  1298. }
  1299. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  1300. // Cannot mix-and-match positional and non-positional arguments.
  1301. S.Diag(getLocationOfByte(CS.getStart()),
  1302. diag::warn_format_mix_positional_nonpositional_args)
  1303. << getSpecifierRange(startSpecifier, specifierLen);
  1304. return false;
  1305. }
  1306. }
  1307. // First check if the field width, precision, and conversion specifier
  1308. // have matching data arguments.
  1309. if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
  1310. startSpecifier, specifierLen)) {
  1311. return false;
  1312. }
  1313. if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
  1314. startSpecifier, specifierLen)) {
  1315. return false;
  1316. }
  1317. if (!CS.consumesDataArgument()) {
  1318. // FIXME: Technically specifying a precision or field width here
  1319. // makes no sense. Worth issuing a warning at some point.
  1320. return true;
  1321. }
  1322. // Consume the argument.
  1323. unsigned argIndex = FS.getArgIndex();
  1324. if (argIndex < NumDataArgs) {
  1325. // The check to see if the argIndex is valid will come later.
  1326. // We set the bit here because we may exit early from this
  1327. // function if we encounter some other error.
  1328. CoveredArgs.set(argIndex);
  1329. }
  1330. // Check for using an Objective-C specific conversion specifier
  1331. // in a non-ObjC literal.
  1332. if (!IsObjCLiteral && CS.isObjCArg()) {
  1333. return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
  1334. specifierLen);
  1335. }
  1336. // Check for invalid use of field width
  1337. if (!FS.hasValidFieldWidth()) {
  1338. HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
  1339. startSpecifier, specifierLen);
  1340. }
  1341. // Check for invalid use of precision
  1342. if (!FS.hasValidPrecision()) {
  1343. HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
  1344. startSpecifier, specifierLen);
  1345. }
  1346. // Check each flag does not conflict with any other component.
  1347. if (!FS.hasValidThousandsGroupingPrefix())
  1348. HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
  1349. if (!FS.hasValidLeadingZeros())
  1350. HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
  1351. if (!FS.hasValidPlusPrefix())
  1352. HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
  1353. if (!FS.hasValidSpacePrefix())
  1354. HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
  1355. if (!FS.hasValidAlternativeForm())
  1356. HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
  1357. if (!FS.hasValidLeftJustified())
  1358. HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
  1359. // Check that flags are not ignored by another flag
  1360. if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
  1361. HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
  1362. startSpecifier, specifierLen);
  1363. if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
  1364. HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
  1365. startSpecifier, specifierLen);
  1366. // Check the length modifier is valid with the given conversion specifier.
  1367. const LengthModifier &LM = FS.getLengthModifier();
  1368. if (!FS.hasValidLengthModifier())
  1369. S.Diag(getLocationOfByte(LM.getStart()),
  1370. diag::warn_format_nonsensical_length)
  1371. << LM.toString() << CS.toString()
  1372. << getSpecifierRange(startSpecifier, specifierLen)
  1373. << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
  1374. LM.getLength()));
  1375. // Are we using '%n'?
  1376. if (CS.getKind() == ConversionSpecifier::nArg) {
  1377. // Issue a warning about this being a possible security issue.
  1378. S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
  1379. << getSpecifierRange(startSpecifier, specifierLen);
  1380. // Continue checking the other format specifiers.
  1381. return true;
  1382. }
  1383. // The remaining checks depend on the data arguments.
  1384. if (HasVAListArg)
  1385. return true;
  1386. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  1387. return false;
  1388. // Now type check the data expression that matches the
  1389. // format specifier.
  1390. const Expr *Ex = getDataArg(argIndex);
  1391. const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
  1392. if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
  1393. // Check if we didn't match because of an implicit cast from a 'char'
  1394. // or 'short' to an 'int'. This is done because printf is a varargs
  1395. // function.
  1396. if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
  1397. if (ICE->getType() == S.Context.IntTy) {
  1398. // All further checking is done on the subexpression.
  1399. Ex = ICE->getSubExpr();
  1400. if (ATR.matchesType(S.Context, Ex->getType()))
  1401. return true;
  1402. }
  1403. // We may be able to offer a FixItHint if it is a supported type.
  1404. PrintfSpecifier fixedFS = FS;
  1405. bool success = fixedFS.fixType(Ex->getType());
  1406. if (success) {
  1407. // Get the fix string from the fixed format specifier
  1408. llvm::SmallString<128> buf;
  1409. llvm::raw_svector_ostream os(buf);
  1410. fixedFS.toString(os);
  1411. // FIXME: getRepresentativeType() perhaps should return a string
  1412. // instead of a QualType to better handle when the representative
  1413. // type is 'wint_t' (which is defined in the system headers).
  1414. S.Diag(getLocationOfByte(CS.getStart()),
  1415. diag::warn_printf_conversion_argument_type_mismatch)
  1416. << ATR.getRepresentativeType(S.Context) << Ex->getType()
  1417. << getSpecifierRange(startSpecifier, specifierLen)
  1418. << Ex->getSourceRange()
  1419. << FixItHint::CreateReplacement(
  1420. getSpecifierRange(startSpecifier, specifierLen),
  1421. os.str());
  1422. }
  1423. else {
  1424. S.Diag(getLocationOfByte(CS.getStart()),
  1425. diag::warn_printf_conversion_argument_type_mismatch)
  1426. << ATR.getRepresentativeType(S.Context) << Ex->getType()
  1427. << getSpecifierRange(startSpecifier, specifierLen)
  1428. << Ex->getSourceRange();
  1429. }
  1430. }
  1431. return true;
  1432. }
  1433. //===--- CHECK: Scanf format string checking ------------------------------===//
  1434. namespace {
  1435. class CheckScanfHandler : public CheckFormatHandler {
  1436. public:
  1437. CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
  1438. const Expr *origFormatExpr, unsigned firstDataArg,
  1439. unsigned numDataArgs, bool isObjCLiteral,
  1440. const char *beg, bool hasVAListArg,
  1441. const CallExpr *theCall, unsigned formatIdx)
  1442. : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
  1443. numDataArgs, isObjCLiteral, beg, hasVAListArg,
  1444. theCall, formatIdx) {}
  1445. bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
  1446. const char *startSpecifier,
  1447. unsigned specifierLen);
  1448. bool HandleInvalidScanfConversionSpecifier(
  1449. const analyze_scanf::ScanfSpecifier &FS,
  1450. const char *startSpecifier,
  1451. unsigned specifierLen);
  1452. void HandleIncompleteScanList(const char *start, const char *end);
  1453. };
  1454. }
  1455. void CheckScanfHandler::HandleIncompleteScanList(const char *start,
  1456. const char *end) {
  1457. S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
  1458. << getSpecifierRange(start, end - start);
  1459. }
  1460. bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
  1461. const analyze_scanf::ScanfSpecifier &FS,
  1462. const char *startSpecifier,
  1463. unsigned specifierLen) {
  1464. const analyze_scanf::ScanfConversionSpecifier &CS =
  1465. FS.getConversionSpecifier();
  1466. return HandleInvalidConversionSpecifier(FS.getArgIndex(),
  1467. getLocationOfByte(CS.getStart()),
  1468. startSpecifier, specifierLen,
  1469. CS.getStart(), CS.getLength());
  1470. }
  1471. bool CheckScanfHandler::HandleScanfSpecifier(
  1472. const analyze_scanf::ScanfSpecifier &FS,
  1473. const char *startSpecifier,
  1474. unsigned specifierLen) {
  1475. using namespace analyze_scanf;
  1476. using namespace analyze_format_string;
  1477. const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
  1478. // Handle case where '%' and '*' don't consume an argument. These shouldn't
  1479. // be used to decide if we are using positional arguments consistently.
  1480. if (FS.consumesDataArgument()) {
  1481. if (atFirstArg) {
  1482. atFirstArg = false;
  1483. usesPositionalArgs = FS.usesPositionalArg();
  1484. }
  1485. else if (usesPositionalArgs != FS.usesPositionalArg()) {
  1486. // Cannot mix-and-match positional and non-positional arguments.
  1487. S.Diag(getLocationOfByte(CS.getStart()),
  1488. diag::warn_format_mix_positional_nonpositional_args)
  1489. << getSpecifierRange(startSpecifier, specifierLen);
  1490. return false;
  1491. }
  1492. }
  1493. // Check if the field with is non-zero.
  1494. const OptionalAmount &Amt = FS.getFieldWidth();
  1495. if (Amt.getHowSpecified() == OptionalAmount::Constant) {
  1496. if (Amt.getConstantAmount() == 0) {
  1497. const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
  1498. Amt.getConstantLength());
  1499. S.Diag(getLocationOfByte(Amt.getStart()),
  1500. diag::warn_scanf_nonzero_width)
  1501. << R << FixItHint::CreateRemoval(R);
  1502. }
  1503. }
  1504. if (!FS.consumesDataArgument()) {
  1505. // FIXME: Technically specifying a precision or field width here
  1506. // makes no sense. Worth issuing a warning at some point.
  1507. return true;
  1508. }
  1509. // Consume the argument.
  1510. unsigned argIndex = FS.getArgIndex();
  1511. if (argIndex < NumDataArgs) {
  1512. // The check to see if the argIndex is valid will come later.
  1513. // We set the bit here because we may exit early from this
  1514. // function if we encounter some other error.
  1515. CoveredArgs.set(argIndex);
  1516. }
  1517. // Check the length modifier is valid with the given conversion specifier.
  1518. const LengthModifier &LM = FS.getLengthModifier();
  1519. if (!FS.hasValidLengthModifier()) {
  1520. S.Diag(getLocationOfByte(LM.getStart()),
  1521. diag::warn_format_nonsensical_length)
  1522. << LM.toString() << CS.toString()
  1523. << getSpecifierRange(startSpecifier, specifierLen)
  1524. << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
  1525. LM.getLength()));
  1526. }
  1527. // The remaining checks depend on the data arguments.
  1528. if (HasVAListArg)
  1529. return true;
  1530. if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
  1531. return false;
  1532. // FIXME: Check that the argument type matches the format specifier.
  1533. return true;
  1534. }
  1535. void Sema::CheckFormatString(const StringLiteral *FExpr,
  1536. const Expr *OrigFormatExpr,
  1537. const CallExpr *TheCall, bool HasVAListArg,
  1538. unsigned format_idx, unsigned firstDataArg,
  1539. bool isPrintf) {
  1540. // CHECK: is the format string a wide literal?
  1541. if (FExpr->isWide()) {
  1542. Diag(FExpr->getLocStart(),
  1543. diag::warn_format_string_is_wide_literal)
  1544. << OrigFormatExpr->getSourceRange();
  1545. return;
  1546. }
  1547. // Str - The format string. NOTE: this is NOT null-terminated!
  1548. llvm::StringRef StrRef = FExpr->getString();
  1549. const char *Str = StrRef.data();
  1550. unsigned StrLen = StrRef.size();
  1551. // CHECK: empty format string?
  1552. if (StrLen == 0) {
  1553. Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
  1554. << OrigFormatExpr->getSourceRange();
  1555. return;
  1556. }
  1557. if (isPrintf) {
  1558. CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  1559. TheCall->getNumArgs() - firstDataArg,
  1560. isa<ObjCStringLiteral>(OrigFormatExpr), Str,
  1561. HasVAListArg, TheCall, format_idx);
  1562. if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
  1563. H.DoneProcessing();
  1564. }
  1565. else {
  1566. CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
  1567. TheCall->getNumArgs() - firstDataArg,
  1568. isa<ObjCStringLiteral>(OrigFormatExpr), Str,
  1569. HasVAListArg, TheCall, format_idx);
  1570. if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
  1571. H.DoneProcessing();
  1572. }
  1573. }
  1574. //===--- CHECK: Standard memory functions ---------------------------------===//
  1575. /// \brief Determine whether the given type is a dynamic class type (e.g.,
  1576. /// whether it has a vtable).
  1577. static bool isDynamicClassType(QualType T) {
  1578. if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
  1579. if (CXXRecordDecl *Definition = Record->getDefinition())
  1580. if (Definition->isDynamicClass())
  1581. return true;
  1582. return false;
  1583. }
  1584. /// \brief If E is a sizeof expression, returns the expression's type in
  1585. /// OutType.
  1586. static bool sizeofExprType(const Expr* E, QualType *OutType) {
  1587. if (const UnaryExprOrTypeTraitExpr *SizeOf =
  1588. dyn_cast<UnaryExprOrTypeTraitExpr>(E)) {
  1589. if (SizeOf->getKind() != clang::UETT_SizeOf)
  1590. return false;
  1591. *OutType = SizeOf->getTypeOfArgument();
  1592. return true;
  1593. }
  1594. return false;
  1595. }
  1596. /// \brief Check for dangerous or invalid arguments to memset().
  1597. ///
  1598. /// This issues warnings on known problematic, dangerous or unspecified
  1599. /// arguments to the standard 'memset', 'memcpy', and 'memmove' function calls.
  1600. ///
  1601. /// \param Call The call expression to diagnose.
  1602. void Sema::CheckMemsetcpymoveArguments(const CallExpr *Call,
  1603. const IdentifierInfo *FnName) {
  1604. // It is possible to have a non-standard definition of memset. Validate
  1605. // we have the proper number of arguments, and if not, abort further
  1606. // checking.
  1607. if (Call->getNumArgs() != 3)
  1608. return;
  1609. unsigned LastArg = FnName->isStr("memset")? 1 : 2;
  1610. const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
  1611. for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
  1612. const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
  1613. SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
  1614. QualType DestTy = Dest->getType();
  1615. if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
  1616. QualType PointeeTy = DestPtrTy->getPointeeType();
  1617. if (PointeeTy->isVoidType())
  1618. continue;
  1619. // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p).
  1620. QualType SizeofTy;
  1621. if (sizeofExprType(LenExpr, &SizeofTy) &&
  1622. Context.typesAreCompatible(SizeofTy, DestTy)) {
  1623. // Note: This complains about sizeof(typeof(p)) as well.
  1624. SourceLocation loc = LenExpr->getSourceRange().getBegin();
  1625. Diag(loc, diag::warn_sizeof_pointer)
  1626. << SizeofTy << PointeeTy << ArgIdx << FnName;
  1627. break;
  1628. }
  1629. unsigned DiagID;
  1630. // Always complain about dynamic classes.
  1631. if (isDynamicClassType(PointeeTy))
  1632. DiagID = diag::warn_dyn_class_memaccess;
  1633. else if (PointeeTy.hasNonTrivialObjCLifetime() &&
  1634. !FnName->isStr("memset"))
  1635. DiagID = diag::warn_arc_object_memaccess;
  1636. else
  1637. continue;
  1638. DiagRuntimeBehavior(
  1639. Dest->getExprLoc(), Dest,
  1640. PDiag(DiagID)
  1641. << ArgIdx << FnName << PointeeTy
  1642. << Call->getCallee()->getSourceRange());
  1643. DiagRuntimeBehavior(
  1644. Dest->getExprLoc(), Dest,
  1645. PDiag(diag::note_bad_memaccess_silence)
  1646. << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
  1647. break;
  1648. }
  1649. }
  1650. }
  1651. //===--- CHECK: Return Address of Stack Variable --------------------------===//
  1652. static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
  1653. static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
  1654. /// CheckReturnStackAddr - Check if a return statement returns the address
  1655. /// of a stack variable.
  1656. void
  1657. Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
  1658. SourceLocation ReturnLoc) {
  1659. Expr *stackE = 0;
  1660. llvm::SmallVector<DeclRefExpr *, 8> refVars;
  1661. // Perform checking for returned stack addresses, local blocks,
  1662. // label addresses or references to temporaries.
  1663. if (lhsType->isPointerType() ||
  1664. (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
  1665. stackE = EvalAddr(RetValExp, refVars);
  1666. } else if (lhsType->isReferenceType()) {
  1667. stackE = EvalVal(RetValExp, refVars);
  1668. }
  1669. if (stackE == 0)
  1670. return; // Nothing suspicious was found.
  1671. SourceLocation diagLoc;
  1672. SourceRange diagRange;
  1673. if (refVars.empty()) {
  1674. diagLoc = stackE->getLocStart();
  1675. diagRange = stackE->getSourceRange();
  1676. } else {
  1677. // We followed through a reference variable. 'stackE' contains the
  1678. // problematic expression but we will warn at the return statement pointing
  1679. // at the reference variable. We will later display the "trail" of
  1680. // reference variables using notes.
  1681. diagLoc = refVars[0]->getLocStart();
  1682. diagRange = refVars[0]->getSourceRange();
  1683. }
  1684. if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
  1685. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
  1686. : diag::warn_ret_stack_addr)
  1687. << DR->getDecl()->getDeclName() << diagRange;
  1688. } else if (isa<BlockExpr>(stackE)) { // local block.
  1689. Diag(diagLoc, diag::err_ret_local_block) << diagRange;
  1690. } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
  1691. Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
  1692. } else { // local temporary.
  1693. Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
  1694. : diag::warn_ret_local_temp_addr)
  1695. << diagRange;
  1696. }
  1697. // Display the "trail" of reference variables that we followed until we
  1698. // found the problematic expression using notes.
  1699. for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
  1700. VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
  1701. // If this var binds to another reference var, show the range of the next
  1702. // var, otherwise the var binds to the problematic expression, in which case
  1703. // show the range of the expression.
  1704. SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
  1705. : stackE->getSourceRange();
  1706. Diag(VD->getLocation(), diag::note_ref_var_local_bind)
  1707. << VD->getDeclName() << range;
  1708. }
  1709. }
  1710. /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
  1711. /// check if the expression in a return statement evaluates to an address
  1712. /// to a location on the stack, a local block, an address of a label, or a
  1713. /// reference to local temporary. The recursion is used to traverse the
  1714. /// AST of the return expression, with recursion backtracking when we
  1715. /// encounter a subexpression that (1) clearly does not lead to one of the
  1716. /// above problematic expressions (2) is something we cannot determine leads to
  1717. /// a problematic expression based on such local checking.
  1718. ///
  1719. /// Both EvalAddr and EvalVal follow through reference variables to evaluate
  1720. /// the expression that they point to. Such variables are added to the
  1721. /// 'refVars' vector so that we know what the reference variable "trail" was.
  1722. ///
  1723. /// EvalAddr processes expressions that are pointers that are used as
  1724. /// references (and not L-values). EvalVal handles all other values.
  1725. /// At the base case of the recursion is a check for the above problematic
  1726. /// expressions.
  1727. ///
  1728. /// This implementation handles:
  1729. ///
  1730. /// * pointer-to-pointer casts
  1731. /// * implicit conversions from array references to pointers
  1732. /// * taking the address of fields
  1733. /// * arbitrary interplay between "&" and "*" operators
  1734. /// * pointer arithmetic from an address of a stack variable
  1735. /// * taking the address of an array element where the array is on the stack
  1736. static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
  1737. if (E->isTypeDependent())
  1738. return NULL;
  1739. // We should only be called for evaluating pointer expressions.
  1740. assert((E->getType()->isAnyPointerType() ||
  1741. E->getType()->isBlockPointerType() ||
  1742. E->getType()->isObjCQualifiedIdType()) &&
  1743. "EvalAddr only works on pointers");
  1744. E = E->IgnoreParens();
  1745. // Our "symbolic interpreter" is just a dispatch off the currently
  1746. // viewed AST node. We then recursively traverse the AST by calling
  1747. // EvalAddr and EvalVal appropriately.
  1748. switch (E->getStmtClass()) {
  1749. case Stmt::DeclRefExprClass: {
  1750. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  1751. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  1752. // If this is a reference variable, follow through to the expression that
  1753. // it points to.
  1754. if (V->hasLocalStorage() &&
  1755. V->getType()->isReferenceType() && V->hasInit()) {
  1756. // Add the reference variable to the "trail".
  1757. refVars.push_back(DR);
  1758. return EvalAddr(V->getInit(), refVars);
  1759. }
  1760. return NULL;
  1761. }
  1762. case Stmt::UnaryOperatorClass: {
  1763. // The only unary operator that make sense to handle here
  1764. // is AddrOf. All others don't make sense as pointers.
  1765. UnaryOperator *U = cast<UnaryOperator>(E);
  1766. if (U->getOpcode() == UO_AddrOf)
  1767. return EvalVal(U->getSubExpr(), refVars);
  1768. else
  1769. return NULL;
  1770. }
  1771. case Stmt::BinaryOperatorClass: {
  1772. // Handle pointer arithmetic. All other binary operators are not valid
  1773. // in this context.
  1774. BinaryOperator *B = cast<BinaryOperator>(E);
  1775. BinaryOperatorKind op = B->getOpcode();
  1776. if (op != BO_Add && op != BO_Sub)
  1777. return NULL;
  1778. Expr *Base = B->getLHS();
  1779. // Determine which argument is the real pointer base. It could be
  1780. // the RHS argument instead of the LHS.
  1781. if (!Base->getType()->isPointerType()) Base = B->getRHS();
  1782. assert (Base->getType()->isPointerType());
  1783. return EvalAddr(Base, refVars);
  1784. }
  1785. // For conditional operators we need to see if either the LHS or RHS are
  1786. // valid DeclRefExpr*s. If one of them is valid, we return it.
  1787. case Stmt::ConditionalOperatorClass: {
  1788. ConditionalOperator *C = cast<ConditionalOperator>(E);
  1789. // Handle the GNU extension for missing LHS.
  1790. if (Expr *lhsExpr = C->getLHS()) {
  1791. // In C++, we can have a throw-expression, which has 'void' type.
  1792. if (!lhsExpr->getType()->isVoidType())
  1793. if (Expr* LHS = EvalAddr(lhsExpr, refVars))
  1794. return LHS;
  1795. }
  1796. // In C++, we can have a throw-expression, which has 'void' type.
  1797. if (C->getRHS()->getType()->isVoidType())
  1798. return NULL;
  1799. return EvalAddr(C->getRHS(), refVars);
  1800. }
  1801. case Stmt::BlockExprClass:
  1802. if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
  1803. return E; // local block.
  1804. return NULL;
  1805. case Stmt::AddrLabelExprClass:
  1806. return E; // address of label.
  1807. // For casts, we need to handle conversions from arrays to
  1808. // pointer values, and pointer-to-pointer conversions.
  1809. case Stmt::ImplicitCastExprClass:
  1810. case Stmt::CStyleCastExprClass:
  1811. case Stmt::CXXFunctionalCastExprClass:
  1812. case Stmt::ObjCBridgedCastExprClass: {
  1813. Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
  1814. QualType T = SubExpr->getType();
  1815. if (SubExpr->getType()->isPointerType() ||
  1816. SubExpr->getType()->isBlockPointerType() ||
  1817. SubExpr->getType()->isObjCQualifiedIdType())
  1818. return EvalAddr(SubExpr, refVars);
  1819. else if (T->isArrayType())
  1820. return EvalVal(SubExpr, refVars);
  1821. else
  1822. return 0;
  1823. }
  1824. // C++ casts. For dynamic casts, static casts, and const casts, we
  1825. // are always converting from a pointer-to-pointer, so we just blow
  1826. // through the cast. In the case the dynamic cast doesn't fail (and
  1827. // return NULL), we take the conservative route and report cases
  1828. // where we return the address of a stack variable. For Reinterpre
  1829. // FIXME: The comment about is wrong; we're not always converting
  1830. // from pointer to pointer. I'm guessing that this code should also
  1831. // handle references to objects.
  1832. case Stmt::CXXStaticCastExprClass:
  1833. case Stmt::CXXDynamicCastExprClass:
  1834. case Stmt::CXXConstCastExprClass:
  1835. case Stmt::CXXReinterpretCastExprClass: {
  1836. Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
  1837. if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
  1838. return EvalAddr(S, refVars);
  1839. else
  1840. return NULL;
  1841. }
  1842. // Everything else: we simply don't reason about them.
  1843. default:
  1844. return NULL;
  1845. }
  1846. }
  1847. /// EvalVal - This function is complements EvalAddr in the mutual recursion.
  1848. /// See the comments for EvalAddr for more details.
  1849. static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
  1850. do {
  1851. // We should only be called for evaluating non-pointer expressions, or
  1852. // expressions with a pointer type that are not used as references but instead
  1853. // are l-values (e.g., DeclRefExpr with a pointer type).
  1854. // Our "symbolic interpreter" is just a dispatch off the currently
  1855. // viewed AST node. We then recursively traverse the AST by calling
  1856. // EvalAddr and EvalVal appropriately.
  1857. E = E->IgnoreParens();
  1858. switch (E->getStmtClass()) {
  1859. case Stmt::ImplicitCastExprClass: {
  1860. ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
  1861. if (IE->getValueKind() == VK_LValue) {
  1862. E = IE->getSubExpr();
  1863. continue;
  1864. }
  1865. return NULL;
  1866. }
  1867. case Stmt::DeclRefExprClass: {
  1868. // When we hit a DeclRefExpr we are looking at code that refers to a
  1869. // variable's name. If it's not a reference variable we check if it has
  1870. // local storage within the function, and if so, return the expression.
  1871. DeclRefExpr *DR = cast<DeclRefExpr>(E);
  1872. if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
  1873. if (V->hasLocalStorage()) {
  1874. if (!V->getType()->isReferenceType())
  1875. return DR;
  1876. // Reference variable, follow through to the expression that
  1877. // it points to.
  1878. if (V->hasInit()) {
  1879. // Add the reference variable to the "trail".
  1880. refVars.push_back(DR);
  1881. return EvalVal(V->getInit(), refVars);
  1882. }
  1883. }
  1884. return NULL;
  1885. }
  1886. case Stmt::UnaryOperatorClass: {
  1887. // The only unary operator that make sense to handle here
  1888. // is Deref. All others don't resolve to a "name." This includes
  1889. // handling all sorts of rvalues passed to a unary operator.
  1890. UnaryOperator *U = cast<UnaryOperator>(E);
  1891. if (U->getOpcode() == UO_Deref)
  1892. return EvalAddr(U->getSubExpr(), refVars);
  1893. return NULL;
  1894. }
  1895. case Stmt::ArraySubscriptExprClass: {
  1896. // Array subscripts are potential references to data on the stack. We
  1897. // retrieve the DeclRefExpr* for the array variable if it indeed
  1898. // has local storage.
  1899. return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
  1900. }
  1901. case Stmt::ConditionalOperatorClass: {
  1902. // For conditional operators we need to see if either the LHS or RHS are
  1903. // non-NULL Expr's. If one is non-NULL, we return it.
  1904. ConditionalOperator *C = cast<ConditionalOperator>(E);
  1905. // Handle the GNU extension for missing LHS.
  1906. if (Expr *lhsExpr = C->getLHS())
  1907. if (Expr *LHS = EvalVal(lhsExpr, refVars))
  1908. return LHS;
  1909. return EvalVal(C->getRHS(), refVars);
  1910. }
  1911. // Accesses to members are potential references to data on the stack.
  1912. case Stmt::MemberExprClass: {
  1913. MemberExpr *M = cast<MemberExpr>(E);
  1914. // Check for indirect access. We only want direct field accesses.
  1915. if (M->isArrow())
  1916. return NULL;
  1917. // Check whether the member type is itself a reference, in which case
  1918. // we're not going to refer to the member, but to what the member refers to.
  1919. if (M->getMemberDecl()->getType()->isReferenceType())
  1920. return NULL;
  1921. return EvalVal(M->getBase(), refVars);
  1922. }
  1923. default:
  1924. // Check that we don't return or take the address of a reference to a
  1925. // temporary. This is only useful in C++.
  1926. if (!E->isTypeDependent() && E->isRValue())
  1927. return E;
  1928. // Everything else: we simply don't reason about them.
  1929. return NULL;
  1930. }
  1931. } while (true);
  1932. }
  1933. //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
  1934. /// Check for comparisons of floating point operands using != and ==.
  1935. /// Issue a warning if these are no self-comparisons, as they are not likely
  1936. /// to do what the programmer intended.
  1937. void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
  1938. bool EmitWarning = true;
  1939. Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
  1940. Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
  1941. // Special case: check for x == x (which is OK).
  1942. // Do not emit warnings for such cases.
  1943. if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
  1944. if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
  1945. if (DRL->getDecl() == DRR->getDecl())
  1946. EmitWarning = false;
  1947. // Special case: check for comparisons against literals that can be exactly
  1948. // represented by APFloat. In such cases, do not emit a warning. This
  1949. // is a heuristic: often comparison against such literals are used to
  1950. // detect if a value in a variable has not changed. This clearly can
  1951. // lead to false negatives.
  1952. if (EmitWarning) {
  1953. if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
  1954. if (FLL->isExact())
  1955. EmitWarning = false;
  1956. } else
  1957. if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
  1958. if (FLR->isExact())
  1959. EmitWarning = false;
  1960. }
  1961. }
  1962. // Check for comparisons with builtin types.
  1963. if (EmitWarning)
  1964. if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
  1965. if (CL->isBuiltinCall(Context))
  1966. EmitWarning = false;
  1967. if (EmitWarning)
  1968. if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
  1969. if (CR->isBuiltinCall(Context))
  1970. EmitWarning = false;
  1971. // Emit the diagnostic.
  1972. if (EmitWarning)
  1973. Diag(loc, diag::warn_floatingpoint_eq)
  1974. << lex->getSourceRange() << rex->getSourceRange();
  1975. }
  1976. //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
  1977. //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
  1978. namespace {
  1979. /// Structure recording the 'active' range of an integer-valued
  1980. /// expression.
  1981. struct IntRange {
  1982. /// The number of bits active in the int.
  1983. unsigned Width;
  1984. /// True if the int is known not to have negative values.
  1985. bool NonNegative;
  1986. IntRange(unsigned Width, bool NonNegative)
  1987. : Width(Width), NonNegative(NonNegative)
  1988. {}
  1989. /// Returns the range of the bool type.
  1990. static IntRange forBoolType() {
  1991. return IntRange(1, true);
  1992. }
  1993. /// Returns the range of an opaque value of the given integral type.
  1994. static IntRange forValueOfType(ASTContext &C, QualType T) {
  1995. return forValueOfCanonicalType(C,
  1996. T->getCanonicalTypeInternal().getTypePtr());
  1997. }
  1998. /// Returns the range of an opaque value of a canonical integral type.
  1999. static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
  2000. assert(T->isCanonicalUnqualified());
  2001. if (const VectorType *VT = dyn_cast<VectorType>(T))
  2002. T = VT->getElementType().getTypePtr();
  2003. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  2004. T = CT->getElementType().getTypePtr();
  2005. // For enum types, use the known bit width of the enumerators.
  2006. if (const EnumType *ET = dyn_cast<EnumType>(T)) {
  2007. EnumDecl *Enum = ET->getDecl();
  2008. if (!Enum->isDefinition())
  2009. return IntRange(C.getIntWidth(QualType(T, 0)), false);
  2010. unsigned NumPositive = Enum->getNumPositiveBits();
  2011. unsigned NumNegative = Enum->getNumNegativeBits();
  2012. return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
  2013. }
  2014. const BuiltinType *BT = cast<BuiltinType>(T);
  2015. assert(BT->isInteger());
  2016. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  2017. }
  2018. /// Returns the "target" range of a canonical integral type, i.e.
  2019. /// the range of values expressible in the type.
  2020. ///
  2021. /// This matches forValueOfCanonicalType except that enums have the
  2022. /// full range of their type, not the range of their enumerators.
  2023. static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
  2024. assert(T->isCanonicalUnqualified());
  2025. if (const VectorType *VT = dyn_cast<VectorType>(T))
  2026. T = VT->getElementType().getTypePtr();
  2027. if (const ComplexType *CT = dyn_cast<ComplexType>(T))
  2028. T = CT->getElementType().getTypePtr();
  2029. if (const EnumType *ET = dyn_cast<EnumType>(T))
  2030. T = ET->getDecl()->getIntegerType().getTypePtr();
  2031. const BuiltinType *BT = cast<BuiltinType>(T);
  2032. assert(BT->isInteger());
  2033. return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
  2034. }
  2035. /// Returns the supremum of two ranges: i.e. their conservative merge.
  2036. static IntRange join(IntRange L, IntRange R) {
  2037. return IntRange(std::max(L.Width, R.Width),
  2038. L.NonNegative && R.NonNegative);
  2039. }
  2040. /// Returns the infinum of two ranges: i.e. their aggressive merge.
  2041. static IntRange meet(IntRange L, IntRange R) {
  2042. return IntRange(std::min(L.Width, R.Width),
  2043. L.NonNegative || R.NonNegative);
  2044. }
  2045. };
  2046. IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
  2047. if (value.isSigned() && value.isNegative())
  2048. return IntRange(value.getMinSignedBits(), false);
  2049. if (value.getBitWidth() > MaxWidth)
  2050. value = value.trunc(MaxWidth);
  2051. // isNonNegative() just checks the sign bit without considering
  2052. // signedness.
  2053. return IntRange(value.getActiveBits(), true);
  2054. }
  2055. IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
  2056. unsigned MaxWidth) {
  2057. if (result.isInt())
  2058. return GetValueRange(C, result.getInt(), MaxWidth);
  2059. if (result.isVector()) {
  2060. IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
  2061. for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
  2062. IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
  2063. R = IntRange::join(R, El);
  2064. }
  2065. return R;
  2066. }
  2067. if (result.isComplexInt()) {
  2068. IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
  2069. IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
  2070. return IntRange::join(R, I);
  2071. }
  2072. // This can happen with lossless casts to intptr_t of "based" lvalues.
  2073. // Assume it might use arbitrary bits.
  2074. // FIXME: The only reason we need to pass the type in here is to get
  2075. // the sign right on this one case. It would be nice if APValue
  2076. // preserved this.
  2077. assert(result.isLValue());
  2078. return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
  2079. }
  2080. /// Pseudo-evaluate the given integer expression, estimating the
  2081. /// range of values it might take.
  2082. ///
  2083. /// \param MaxWidth - the width to which the value will be truncated
  2084. IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
  2085. E = E->IgnoreParens();
  2086. // Try a full evaluation first.
  2087. Expr::EvalResult result;
  2088. if (E->Evaluate(result, C))
  2089. return GetValueRange(C, result.Val, E->getType(), MaxWidth);
  2090. // I think we only want to look through implicit casts here; if the
  2091. // user has an explicit widening cast, we should treat the value as
  2092. // being of the new, wider type.
  2093. if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  2094. if (CE->getCastKind() == CK_NoOp)
  2095. return GetExprRange(C, CE->getSubExpr(), MaxWidth);
  2096. IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
  2097. bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
  2098. // Assume that non-integer casts can span the full range of the type.
  2099. if (!isIntegerCast)
  2100. return OutputTypeRange;
  2101. IntRange SubRange
  2102. = GetExprRange(C, CE->getSubExpr(),
  2103. std::min(MaxWidth, OutputTypeRange.Width));
  2104. // Bail out if the subexpr's range is as wide as the cast type.
  2105. if (SubRange.Width >= OutputTypeRange.Width)
  2106. return OutputTypeRange;
  2107. // Otherwise, we take the smaller width, and we're non-negative if
  2108. // either the output type or the subexpr is.
  2109. return IntRange(SubRange.Width,
  2110. SubRange.NonNegative || OutputTypeRange.NonNegative);
  2111. }
  2112. if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
  2113. // If we can fold the condition, just take that operand.
  2114. bool CondResult;
  2115. if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
  2116. return GetExprRange(C, CondResult ? CO->getTrueExpr()
  2117. : CO->getFalseExpr(),
  2118. MaxWidth);
  2119. // Otherwise, conservatively merge.
  2120. IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
  2121. IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
  2122. return IntRange::join(L, R);
  2123. }
  2124. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  2125. switch (BO->getOpcode()) {
  2126. // Boolean-valued operations are single-bit and positive.
  2127. case BO_LAnd:
  2128. case BO_LOr:
  2129. case BO_LT:
  2130. case BO_GT:
  2131. case BO_LE:
  2132. case BO_GE:
  2133. case BO_EQ:
  2134. case BO_NE:
  2135. return IntRange::forBoolType();
  2136. // The type of these compound assignments is the type of the LHS,
  2137. // so the RHS is not necessarily an integer.
  2138. case BO_MulAssign:
  2139. case BO_DivAssign:
  2140. case BO_RemAssign:
  2141. case BO_AddAssign:
  2142. case BO_SubAssign:
  2143. return IntRange::forValueOfType(C, E->getType());
  2144. // Operations with opaque sources are black-listed.
  2145. case BO_PtrMemD:
  2146. case BO_PtrMemI:
  2147. return IntRange::forValueOfType(C, E->getType());
  2148. // Bitwise-and uses the *infinum* of the two source ranges.
  2149. case BO_And:
  2150. case BO_AndAssign:
  2151. return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
  2152. GetExprRange(C, BO->getRHS(), MaxWidth));
  2153. // Left shift gets black-listed based on a judgement call.
  2154. case BO_Shl:
  2155. // ...except that we want to treat '1 << (blah)' as logically
  2156. // positive. It's an important idiom.
  2157. if (IntegerLiteral *I
  2158. = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
  2159. if (I->getValue() == 1) {
  2160. IntRange R = IntRange::forValueOfType(C, E->getType());
  2161. return IntRange(R.Width, /*NonNegative*/ true);
  2162. }
  2163. }
  2164. // fallthrough
  2165. case BO_ShlAssign:
  2166. return IntRange::forValueOfType(C, E->getType());
  2167. // Right shift by a constant can narrow its left argument.
  2168. case BO_Shr:
  2169. case BO_ShrAssign: {
  2170. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  2171. // If the shift amount is a positive constant, drop the width by
  2172. // that much.
  2173. llvm::APSInt shift;
  2174. if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
  2175. shift.isNonNegative()) {
  2176. unsigned zext = shift.getZExtValue();
  2177. if (zext >= L.Width)
  2178. L.Width = (L.NonNegative ? 0 : 1);
  2179. else
  2180. L.Width -= zext;
  2181. }
  2182. return L;
  2183. }
  2184. // Comma acts as its right operand.
  2185. case BO_Comma:
  2186. return GetExprRange(C, BO->getRHS(), MaxWidth);
  2187. // Black-list pointer subtractions.
  2188. case BO_Sub:
  2189. if (BO->getLHS()->getType()->isPointerType())
  2190. return IntRange::forValueOfType(C, E->getType());
  2191. // fallthrough
  2192. default:
  2193. break;
  2194. }
  2195. // Treat every other operator as if it were closed on the
  2196. // narrowest type that encompasses both operands.
  2197. IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
  2198. IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
  2199. return IntRange::join(L, R);
  2200. }
  2201. if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
  2202. switch (UO->getOpcode()) {
  2203. // Boolean-valued operations are white-listed.
  2204. case UO_LNot:
  2205. return IntRange::forBoolType();
  2206. // Operations with opaque sources are black-listed.
  2207. case UO_Deref:
  2208. case UO_AddrOf: // should be impossible
  2209. return IntRange::forValueOfType(C, E->getType());
  2210. default:
  2211. return GetExprRange(C, UO->getSubExpr(), MaxWidth);
  2212. }
  2213. }
  2214. if (dyn_cast<OffsetOfExpr>(E)) {
  2215. IntRange::forValueOfType(C, E->getType());
  2216. }
  2217. FieldDecl *BitField = E->getBitField();
  2218. if (BitField) {
  2219. llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
  2220. unsigned BitWidth = BitWidthAP.getZExtValue();
  2221. return IntRange(BitWidth,
  2222. BitField->getType()->isUnsignedIntegerOrEnumerationType());
  2223. }
  2224. return IntRange::forValueOfType(C, E->getType());
  2225. }
  2226. IntRange GetExprRange(ASTContext &C, Expr *E) {
  2227. return GetExprRange(C, E, C.getIntWidth(E->getType()));
  2228. }
  2229. /// Checks whether the given value, which currently has the given
  2230. /// source semantics, has the same value when coerced through the
  2231. /// target semantics.
  2232. bool IsSameFloatAfterCast(const llvm::APFloat &value,
  2233. const llvm::fltSemantics &Src,
  2234. const llvm::fltSemantics &Tgt) {
  2235. llvm::APFloat truncated = value;
  2236. bool ignored;
  2237. truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
  2238. truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
  2239. return truncated.bitwiseIsEqual(value);
  2240. }
  2241. /// Checks whether the given value, which currently has the given
  2242. /// source semantics, has the same value when coerced through the
  2243. /// target semantics.
  2244. ///
  2245. /// The value might be a vector of floats (or a complex number).
  2246. bool IsSameFloatAfterCast(const APValue &value,
  2247. const llvm::fltSemantics &Src,
  2248. const llvm::fltSemantics &Tgt) {
  2249. if (value.isFloat())
  2250. return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
  2251. if (value.isVector()) {
  2252. for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
  2253. if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
  2254. return false;
  2255. return true;
  2256. }
  2257. assert(value.isComplexFloat());
  2258. return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
  2259. IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
  2260. }
  2261. void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
  2262. static bool IsZero(Sema &S, Expr *E) {
  2263. // Suppress cases where we are comparing against an enum constant.
  2264. if (const DeclRefExpr *DR =
  2265. dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
  2266. if (isa<EnumConstantDecl>(DR->getDecl()))
  2267. return false;
  2268. // Suppress cases where the '0' value is expanded from a macro.
  2269. if (E->getLocStart().isMacroID())
  2270. return false;
  2271. llvm::APSInt Value;
  2272. return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
  2273. }
  2274. static bool HasEnumType(Expr *E) {
  2275. // Strip off implicit integral promotions.
  2276. while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
  2277. if (ICE->getCastKind() != CK_IntegralCast &&
  2278. ICE->getCastKind() != CK_NoOp)
  2279. break;
  2280. E = ICE->getSubExpr();
  2281. }
  2282. return E->getType()->isEnumeralType();
  2283. }
  2284. void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
  2285. BinaryOperatorKind op = E->getOpcode();
  2286. if (E->isValueDependent())
  2287. return;
  2288. if (op == BO_LT && IsZero(S, E->getRHS())) {
  2289. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  2290. << "< 0" << "false" << HasEnumType(E->getLHS())
  2291. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  2292. } else if (op == BO_GE && IsZero(S, E->getRHS())) {
  2293. S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
  2294. << ">= 0" << "true" << HasEnumType(E->getLHS())
  2295. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  2296. } else if (op == BO_GT && IsZero(S, E->getLHS())) {
  2297. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  2298. << "0 >" << "false" << HasEnumType(E->getRHS())
  2299. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  2300. } else if (op == BO_LE && IsZero(S, E->getLHS())) {
  2301. S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
  2302. << "0 <=" << "true" << HasEnumType(E->getRHS())
  2303. << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
  2304. }
  2305. }
  2306. /// Analyze the operands of the given comparison. Implements the
  2307. /// fallback case from AnalyzeComparison.
  2308. void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
  2309. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  2310. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  2311. }
  2312. /// \brief Implements -Wsign-compare.
  2313. ///
  2314. /// \param lex the left-hand expression
  2315. /// \param rex the right-hand expression
  2316. /// \param OpLoc the location of the joining operator
  2317. /// \param BinOpc binary opcode or 0
  2318. void AnalyzeComparison(Sema &S, BinaryOperator *E) {
  2319. // The type the comparison is being performed in.
  2320. QualType T = E->getLHS()->getType();
  2321. assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
  2322. && "comparison with mismatched types");
  2323. // We don't do anything special if this isn't an unsigned integral
  2324. // comparison: we're only interested in integral comparisons, and
  2325. // signed comparisons only happen in cases we don't care to warn about.
  2326. //
  2327. // We also don't care about value-dependent expressions or expressions
  2328. // whose result is a constant.
  2329. if (!T->hasUnsignedIntegerRepresentation()
  2330. || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
  2331. return AnalyzeImpConvsInComparison(S, E);
  2332. Expr *lex = E->getLHS()->IgnoreParenImpCasts();
  2333. Expr *rex = E->getRHS()->IgnoreParenImpCasts();
  2334. // Check to see if one of the (unmodified) operands is of different
  2335. // signedness.
  2336. Expr *signedOperand, *unsignedOperand;
  2337. if (lex->getType()->hasSignedIntegerRepresentation()) {
  2338. assert(!rex->getType()->hasSignedIntegerRepresentation() &&
  2339. "unsigned comparison between two signed integer expressions?");
  2340. signedOperand = lex;
  2341. unsignedOperand = rex;
  2342. } else if (rex->getType()->hasSignedIntegerRepresentation()) {
  2343. signedOperand = rex;
  2344. unsignedOperand = lex;
  2345. } else {
  2346. CheckTrivialUnsignedComparison(S, E);
  2347. return AnalyzeImpConvsInComparison(S, E);
  2348. }
  2349. // Otherwise, calculate the effective range of the signed operand.
  2350. IntRange signedRange = GetExprRange(S.Context, signedOperand);
  2351. // Go ahead and analyze implicit conversions in the operands. Note
  2352. // that we skip the implicit conversions on both sides.
  2353. AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
  2354. AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
  2355. // If the signed range is non-negative, -Wsign-compare won't fire,
  2356. // but we should still check for comparisons which are always true
  2357. // or false.
  2358. if (signedRange.NonNegative)
  2359. return CheckTrivialUnsignedComparison(S, E);
  2360. // For (in)equality comparisons, if the unsigned operand is a
  2361. // constant which cannot collide with a overflowed signed operand,
  2362. // then reinterpreting the signed operand as unsigned will not
  2363. // change the result of the comparison.
  2364. if (E->isEqualityOp()) {
  2365. unsigned comparisonWidth = S.Context.getIntWidth(T);
  2366. IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
  2367. // We should never be unable to prove that the unsigned operand is
  2368. // non-negative.
  2369. assert(unsignedRange.NonNegative && "unsigned range includes negative?");
  2370. if (unsignedRange.Width < comparisonWidth)
  2371. return;
  2372. }
  2373. S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
  2374. << lex->getType() << rex->getType()
  2375. << lex->getSourceRange() << rex->getSourceRange();
  2376. }
  2377. /// Analyzes an attempt to assign the given value to a bitfield.
  2378. ///
  2379. /// Returns true if there was something fishy about the attempt.
  2380. bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
  2381. SourceLocation InitLoc) {
  2382. assert(Bitfield->isBitField());
  2383. if (Bitfield->isInvalidDecl())
  2384. return false;
  2385. // White-list bool bitfields.
  2386. if (Bitfield->getType()->isBooleanType())
  2387. return false;
  2388. // Ignore value- or type-dependent expressions.
  2389. if (Bitfield->getBitWidth()->isValueDependent() ||
  2390. Bitfield->getBitWidth()->isTypeDependent() ||
  2391. Init->isValueDependent() ||
  2392. Init->isTypeDependent())
  2393. return false;
  2394. Expr *OriginalInit = Init->IgnoreParenImpCasts();
  2395. llvm::APSInt Width(32);
  2396. Expr::EvalResult InitValue;
  2397. if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
  2398. !OriginalInit->Evaluate(InitValue, S.Context) ||
  2399. !InitValue.Val.isInt())
  2400. return false;
  2401. const llvm::APSInt &Value = InitValue.Val.getInt();
  2402. unsigned OriginalWidth = Value.getBitWidth();
  2403. unsigned FieldWidth = Width.getZExtValue();
  2404. if (OriginalWidth <= FieldWidth)
  2405. return false;
  2406. llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
  2407. // It's fairly common to write values into signed bitfields
  2408. // that, if sign-extended, would end up becoming a different
  2409. // value. We don't want to warn about that.
  2410. if (Value.isSigned() && Value.isNegative())
  2411. TruncatedValue = TruncatedValue.sext(OriginalWidth);
  2412. else
  2413. TruncatedValue = TruncatedValue.zext(OriginalWidth);
  2414. if (Value == TruncatedValue)
  2415. return false;
  2416. std::string PrettyValue = Value.toString(10);
  2417. std::string PrettyTrunc = TruncatedValue.toString(10);
  2418. S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
  2419. << PrettyValue << PrettyTrunc << OriginalInit->getType()
  2420. << Init->getSourceRange();
  2421. return true;
  2422. }
  2423. /// Analyze the given simple or compound assignment for warning-worthy
  2424. /// operations.
  2425. void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
  2426. // Just recurse on the LHS.
  2427. AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
  2428. // We want to recurse on the RHS as normal unless we're assigning to
  2429. // a bitfield.
  2430. if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
  2431. if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
  2432. E->getOperatorLoc())) {
  2433. // Recurse, ignoring any implicit conversions on the RHS.
  2434. return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
  2435. E->getOperatorLoc());
  2436. }
  2437. }
  2438. AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
  2439. }
  2440. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  2441. void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
  2442. SourceLocation CContext, unsigned diag) {
  2443. S.Diag(E->getExprLoc(), diag)
  2444. << SourceType << T << E->getSourceRange() << SourceRange(CContext);
  2445. }
  2446. /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
  2447. void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
  2448. unsigned diag) {
  2449. DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
  2450. }
  2451. /// Diagnose an implicit cast from a literal expression. Also attemps to supply
  2452. /// fixit hints when the cast wouldn't lose information to simply write the
  2453. /// expression with the expected type.
  2454. void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
  2455. SourceLocation CContext) {
  2456. // Emit the primary warning first, then try to emit a fixit hint note if
  2457. // reasonable.
  2458. S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
  2459. << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
  2460. const llvm::APFloat &Value = FL->getValue();
  2461. // Don't attempt to fix PPC double double literals.
  2462. if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
  2463. return;
  2464. // Try to convert this exactly to an 64-bit integer. FIXME: It would be
  2465. // nice to support arbitrarily large integers here.
  2466. bool isExact = false;
  2467. uint64_t IntegerPart;
  2468. if (Value.convertToInteger(&IntegerPart, 64, /*isSigned=*/true,
  2469. llvm::APFloat::rmTowardZero, &isExact)
  2470. != llvm::APFloat::opOK || !isExact)
  2471. return;
  2472. llvm::APInt IntegerValue(64, IntegerPart, /*isSigned=*/true);
  2473. std::string LiteralValue = IntegerValue.toString(10, /*isSigned=*/true);
  2474. S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
  2475. << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
  2476. }
  2477. std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
  2478. if (!Range.Width) return "0";
  2479. llvm::APSInt ValueInRange = Value;
  2480. ValueInRange.setIsSigned(!Range.NonNegative);
  2481. ValueInRange = ValueInRange.trunc(Range.Width);
  2482. return ValueInRange.toString(10);
  2483. }
  2484. static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
  2485. SourceManager &smgr = S.Context.getSourceManager();
  2486. return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
  2487. }
  2488. void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
  2489. SourceLocation CC, bool *ICContext = 0) {
  2490. if (E->isTypeDependent() || E->isValueDependent()) return;
  2491. const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
  2492. const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
  2493. if (Source == Target) return;
  2494. if (Target->isDependentType()) return;
  2495. // If the conversion context location is invalid don't complain.
  2496. // We also don't want to emit a warning if the issue occurs from the
  2497. // instantiation of a system macro. The problem is that 'getSpellingLoc()'
  2498. // is slow, so we delay this check as long as possible. Once we detect
  2499. // we are in that scenario, we just return.
  2500. if (CC.isInvalid())
  2501. return;
  2502. // Never diagnose implicit casts to bool.
  2503. if (Target->isSpecificBuiltinType(BuiltinType::Bool))
  2504. return;
  2505. // Strip vector types.
  2506. if (isa<VectorType>(Source)) {
  2507. if (!isa<VectorType>(Target)) {
  2508. if (isFromSystemMacro(S, CC))
  2509. return;
  2510. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
  2511. }
  2512. // If the vector cast is cast between two vectors of the same size, it is
  2513. // a bitcast, not a conversion.
  2514. if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
  2515. return;
  2516. Source = cast<VectorType>(Source)->getElementType().getTypePtr();
  2517. Target = cast<VectorType>(Target)->getElementType().getTypePtr();
  2518. }
  2519. // Strip complex types.
  2520. if (isa<ComplexType>(Source)) {
  2521. if (!isa<ComplexType>(Target)) {
  2522. if (isFromSystemMacro(S, CC))
  2523. return;
  2524. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
  2525. }
  2526. Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
  2527. Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
  2528. }
  2529. const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
  2530. const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
  2531. // If the source is floating point...
  2532. if (SourceBT && SourceBT->isFloatingPoint()) {
  2533. // ...and the target is floating point...
  2534. if (TargetBT && TargetBT->isFloatingPoint()) {
  2535. // ...then warn if we're dropping FP rank.
  2536. // Builtin FP kinds are ordered by increasing FP rank.
  2537. if (SourceBT->getKind() > TargetBT->getKind()) {
  2538. // Don't warn about float constants that are precisely
  2539. // representable in the target type.
  2540. Expr::EvalResult result;
  2541. if (E->Evaluate(result, S.Context)) {
  2542. // Value might be a float, a float vector, or a float complex.
  2543. if (IsSameFloatAfterCast(result.Val,
  2544. S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
  2545. S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
  2546. return;
  2547. }
  2548. if (isFromSystemMacro(S, CC))
  2549. return;
  2550. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
  2551. }
  2552. return;
  2553. }
  2554. // If the target is integral, always warn.
  2555. if ((TargetBT && TargetBT->isInteger())) {
  2556. if (isFromSystemMacro(S, CC))
  2557. return;
  2558. Expr *InnerE = E->IgnoreParenImpCasts();
  2559. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
  2560. DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
  2561. } else {
  2562. DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
  2563. }
  2564. }
  2565. return;
  2566. }
  2567. if (!Source->isIntegerType() || !Target->isIntegerType())
  2568. return;
  2569. if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
  2570. == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
  2571. S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
  2572. << E->getSourceRange() << clang::SourceRange(CC);
  2573. return;
  2574. }
  2575. IntRange SourceRange = GetExprRange(S.Context, E);
  2576. IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
  2577. if (SourceRange.Width > TargetRange.Width) {
  2578. // If the source is a constant, use a default-on diagnostic.
  2579. // TODO: this should happen for bitfield stores, too.
  2580. llvm::APSInt Value(32);
  2581. if (E->isIntegerConstantExpr(Value, S.Context)) {
  2582. if (isFromSystemMacro(S, CC))
  2583. return;
  2584. std::string PrettySourceValue = Value.toString(10);
  2585. std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
  2586. S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
  2587. << PrettySourceValue << PrettyTargetValue
  2588. << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
  2589. return;
  2590. }
  2591. // People want to build with -Wshorten-64-to-32 and not -Wconversion.
  2592. if (isFromSystemMacro(S, CC))
  2593. return;
  2594. if (SourceRange.Width == 64 && TargetRange.Width == 32)
  2595. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
  2596. return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
  2597. }
  2598. if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
  2599. (!TargetRange.NonNegative && SourceRange.NonNegative &&
  2600. SourceRange.Width == TargetRange.Width)) {
  2601. if (isFromSystemMacro(S, CC))
  2602. return;
  2603. unsigned DiagID = diag::warn_impcast_integer_sign;
  2604. // Traditionally, gcc has warned about this under -Wsign-compare.
  2605. // We also want to warn about it in -Wconversion.
  2606. // So if -Wconversion is off, use a completely identical diagnostic
  2607. // in the sign-compare group.
  2608. // The conditional-checking code will
  2609. if (ICContext) {
  2610. DiagID = diag::warn_impcast_integer_sign_conditional;
  2611. *ICContext = true;
  2612. }
  2613. return DiagnoseImpCast(S, E, T, CC, DiagID);
  2614. }
  2615. // Diagnose conversions between different enumeration types.
  2616. // In C, we pretend that the type of an EnumConstantDecl is its enumeration
  2617. // type, to give us better diagnostics.
  2618. QualType SourceType = E->getType();
  2619. if (!S.getLangOptions().CPlusPlus) {
  2620. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
  2621. if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  2622. EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
  2623. SourceType = S.Context.getTypeDeclType(Enum);
  2624. Source = S.Context.getCanonicalType(SourceType).getTypePtr();
  2625. }
  2626. }
  2627. if (const EnumType *SourceEnum = Source->getAs<EnumType>())
  2628. if (const EnumType *TargetEnum = Target->getAs<EnumType>())
  2629. if ((SourceEnum->getDecl()->getIdentifier() ||
  2630. SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  2631. (TargetEnum->getDecl()->getIdentifier() ||
  2632. TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
  2633. SourceEnum != TargetEnum) {
  2634. if (isFromSystemMacro(S, CC))
  2635. return;
  2636. return DiagnoseImpCast(S, E, SourceType, T, CC,
  2637. diag::warn_impcast_different_enum_types);
  2638. }
  2639. return;
  2640. }
  2641. void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
  2642. void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
  2643. SourceLocation CC, bool &ICContext) {
  2644. E = E->IgnoreParenImpCasts();
  2645. if (isa<ConditionalOperator>(E))
  2646. return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
  2647. AnalyzeImplicitConversions(S, E, CC);
  2648. if (E->getType() != T)
  2649. return CheckImplicitConversion(S, E, T, CC, &ICContext);
  2650. return;
  2651. }
  2652. void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
  2653. SourceLocation CC = E->getQuestionLoc();
  2654. AnalyzeImplicitConversions(S, E->getCond(), CC);
  2655. bool Suspicious = false;
  2656. CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
  2657. CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
  2658. // If -Wconversion would have warned about either of the candidates
  2659. // for a signedness conversion to the context type...
  2660. if (!Suspicious) return;
  2661. // ...but it's currently ignored...
  2662. if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
  2663. CC))
  2664. return;
  2665. // ...and -Wsign-compare isn't...
  2666. if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
  2667. return;
  2668. // ...then check whether it would have warned about either of the
  2669. // candidates for a signedness conversion to the condition type.
  2670. if (E->getType() != T) {
  2671. Suspicious = false;
  2672. CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
  2673. E->getType(), CC, &Suspicious);
  2674. if (!Suspicious)
  2675. CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
  2676. E->getType(), CC, &Suspicious);
  2677. if (!Suspicious)
  2678. return;
  2679. }
  2680. // If so, emit a diagnostic under -Wsign-compare.
  2681. Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
  2682. Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
  2683. S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
  2684. << lex->getType() << rex->getType()
  2685. << lex->getSourceRange() << rex->getSourceRange();
  2686. }
  2687. /// AnalyzeImplicitConversions - Find and report any interesting
  2688. /// implicit conversions in the given expression. There are a couple
  2689. /// of competing diagnostics here, -Wconversion and -Wsign-compare.
  2690. void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
  2691. QualType T = OrigE->getType();
  2692. Expr *E = OrigE->IgnoreParenImpCasts();
  2693. // For conditional operators, we analyze the arguments as if they
  2694. // were being fed directly into the output.
  2695. if (isa<ConditionalOperator>(E)) {
  2696. ConditionalOperator *CO = cast<ConditionalOperator>(E);
  2697. CheckConditionalOperator(S, CO, T);
  2698. return;
  2699. }
  2700. // Go ahead and check any implicit conversions we might have skipped.
  2701. // The non-canonical typecheck is just an optimization;
  2702. // CheckImplicitConversion will filter out dead implicit conversions.
  2703. if (E->getType() != T)
  2704. CheckImplicitConversion(S, E, T, CC);
  2705. // Now continue drilling into this expression.
  2706. // Skip past explicit casts.
  2707. if (isa<ExplicitCastExpr>(E)) {
  2708. E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
  2709. return AnalyzeImplicitConversions(S, E, CC);
  2710. }
  2711. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
  2712. // Do a somewhat different check with comparison operators.
  2713. if (BO->isComparisonOp())
  2714. return AnalyzeComparison(S, BO);
  2715. // And with assignments and compound assignments.
  2716. if (BO->isAssignmentOp())
  2717. return AnalyzeAssignment(S, BO);
  2718. }
  2719. // These break the otherwise-useful invariant below. Fortunately,
  2720. // we don't really need to recurse into them, because any internal
  2721. // expressions should have been analyzed already when they were
  2722. // built into statements.
  2723. if (isa<StmtExpr>(E)) return;
  2724. // Don't descend into unevaluated contexts.
  2725. if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
  2726. // Now just recurse over the expression's children.
  2727. CC = E->getExprLoc();
  2728. for (Stmt::child_range I = E->children(); I; ++I)
  2729. AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
  2730. }
  2731. } // end anonymous namespace
  2732. /// Diagnoses "dangerous" implicit conversions within the given
  2733. /// expression (which is a full expression). Implements -Wconversion
  2734. /// and -Wsign-compare.
  2735. ///
  2736. /// \param CC the "context" location of the implicit conversion, i.e.
  2737. /// the most location of the syntactic entity requiring the implicit
  2738. /// conversion
  2739. void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
  2740. // Don't diagnose in unevaluated contexts.
  2741. if (ExprEvalContexts.back().Context == Sema::Unevaluated)
  2742. return;
  2743. // Don't diagnose for value- or type-dependent expressions.
  2744. if (E->isTypeDependent() || E->isValueDependent())
  2745. return;
  2746. // This is not the right CC for (e.g.) a variable initialization.
  2747. AnalyzeImplicitConversions(*this, E, CC);
  2748. }
  2749. void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
  2750. FieldDecl *BitField,
  2751. Expr *Init) {
  2752. (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
  2753. }
  2754. /// CheckParmsForFunctionDef - Check that the parameters of the given
  2755. /// function are appropriate for the definition of a function. This
  2756. /// takes care of any checks that cannot be performed on the
  2757. /// declaration itself, e.g., that the types of each of the function
  2758. /// parameters are complete.
  2759. bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
  2760. bool CheckParameterNames) {
  2761. bool HasInvalidParm = false;
  2762. for (; P != PEnd; ++P) {
  2763. ParmVarDecl *Param = *P;
  2764. // C99 6.7.5.3p4: the parameters in a parameter type list in a
  2765. // function declarator that is part of a function definition of
  2766. // that function shall not have incomplete type.
  2767. //
  2768. // This is also C++ [dcl.fct]p6.
  2769. if (!Param->isInvalidDecl() &&
  2770. RequireCompleteType(Param->getLocation(), Param->getType(),
  2771. diag::err_typecheck_decl_incomplete_type)) {
  2772. Param->setInvalidDecl();
  2773. HasInvalidParm = true;
  2774. }
  2775. // C99 6.9.1p5: If the declarator includes a parameter type list, the
  2776. // declaration of each parameter shall include an identifier.
  2777. if (CheckParameterNames &&
  2778. Param->getIdentifier() == 0 &&
  2779. !Param->isImplicit() &&
  2780. !getLangOptions().CPlusPlus)
  2781. Diag(Param->getLocation(), diag::err_parameter_name_omitted);
  2782. // C99 6.7.5.3p12:
  2783. // If the function declarator is not part of a definition of that
  2784. // function, parameters may have incomplete type and may use the [*]
  2785. // notation in their sequences of declarator specifiers to specify
  2786. // variable length array types.
  2787. QualType PType = Param->getOriginalType();
  2788. if (const ArrayType *AT = Context.getAsArrayType(PType)) {
  2789. if (AT->getSizeModifier() == ArrayType::Star) {
  2790. // FIXME: This diagnosic should point the the '[*]' if source-location
  2791. // information is added for it.
  2792. Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
  2793. }
  2794. }
  2795. }
  2796. return HasInvalidParm;
  2797. }
  2798. /// CheckCastAlign - Implements -Wcast-align, which warns when a
  2799. /// pointer cast increases the alignment requirements.
  2800. void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
  2801. // This is actually a lot of work to potentially be doing on every
  2802. // cast; don't do it if we're ignoring -Wcast_align (as is the default).
  2803. if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
  2804. TRange.getBegin())
  2805. == Diagnostic::Ignored)
  2806. return;
  2807. // Ignore dependent types.
  2808. if (T->isDependentType() || Op->getType()->isDependentType())
  2809. return;
  2810. // Require that the destination be a pointer type.
  2811. const PointerType *DestPtr = T->getAs<PointerType>();
  2812. if (!DestPtr) return;
  2813. // If the destination has alignment 1, we're done.
  2814. QualType DestPointee = DestPtr->getPointeeType();
  2815. if (DestPointee->isIncompleteType()) return;
  2816. CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
  2817. if (DestAlign.isOne()) return;
  2818. // Require that the source be a pointer type.
  2819. const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
  2820. if (!SrcPtr) return;
  2821. QualType SrcPointee = SrcPtr->getPointeeType();
  2822. // Whitelist casts from cv void*. We already implicitly
  2823. // whitelisted casts to cv void*, since they have alignment 1.
  2824. // Also whitelist casts involving incomplete types, which implicitly
  2825. // includes 'void'.
  2826. if (SrcPointee->isIncompleteType()) return;
  2827. CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
  2828. if (SrcAlign >= DestAlign) return;
  2829. Diag(TRange.getBegin(), diag::warn_cast_align)
  2830. << Op->getType() << T
  2831. << static_cast<unsigned>(SrcAlign.getQuantity())
  2832. << static_cast<unsigned>(DestAlign.getQuantity())
  2833. << TRange << Op->getSourceRange();
  2834. }
  2835. static void CheckArrayAccess_Check(Sema &S,
  2836. const clang::ArraySubscriptExpr *E) {
  2837. const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
  2838. const ConstantArrayType *ArrayTy =
  2839. S.Context.getAsConstantArrayType(BaseExpr->getType());
  2840. if (!ArrayTy)
  2841. return;
  2842. const Expr *IndexExpr = E->getIdx();
  2843. if (IndexExpr->isValueDependent())
  2844. return;
  2845. llvm::APSInt index;
  2846. if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
  2847. return;
  2848. if (index.isUnsigned() || !index.isNegative()) {
  2849. llvm::APInt size = ArrayTy->getSize();
  2850. if (!size.isStrictlyPositive())
  2851. return;
  2852. if (size.getBitWidth() > index.getBitWidth())
  2853. index = index.sext(size.getBitWidth());
  2854. else if (size.getBitWidth() < index.getBitWidth())
  2855. size = size.sext(index.getBitWidth());
  2856. if (index.slt(size))
  2857. return;
  2858. S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
  2859. S.PDiag(diag::warn_array_index_exceeds_bounds)
  2860. << index.toString(10, true)
  2861. << size.toString(10, true)
  2862. << IndexExpr->getSourceRange());
  2863. } else {
  2864. S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
  2865. S.PDiag(diag::warn_array_index_precedes_bounds)
  2866. << index.toString(10, true)
  2867. << IndexExpr->getSourceRange());
  2868. }
  2869. const NamedDecl *ND = NULL;
  2870. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
  2871. ND = dyn_cast<NamedDecl>(DRE->getDecl());
  2872. if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
  2873. ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
  2874. if (ND)
  2875. S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
  2876. S.PDiag(diag::note_array_index_out_of_bounds)
  2877. << ND->getDeclName());
  2878. }
  2879. void Sema::CheckArrayAccess(const Expr *expr) {
  2880. while (true) {
  2881. expr = expr->IgnoreParens();
  2882. switch (expr->getStmtClass()) {
  2883. case Stmt::ArraySubscriptExprClass:
  2884. CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
  2885. return;
  2886. case Stmt::ConditionalOperatorClass: {
  2887. const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
  2888. if (const Expr *lhs = cond->getLHS())
  2889. CheckArrayAccess(lhs);
  2890. if (const Expr *rhs = cond->getRHS())
  2891. CheckArrayAccess(rhs);
  2892. return;
  2893. }
  2894. default:
  2895. return;
  2896. }
  2897. }
  2898. }
  2899. //===--- CHECK: Objective-C retain cycles ----------------------------------//
  2900. namespace {
  2901. struct RetainCycleOwner {
  2902. RetainCycleOwner() : Variable(0), Indirect(false) {}
  2903. VarDecl *Variable;
  2904. SourceRange Range;
  2905. SourceLocation Loc;
  2906. bool Indirect;
  2907. void setLocsFrom(Expr *e) {
  2908. Loc = e->getExprLoc();
  2909. Range = e->getSourceRange();
  2910. }
  2911. };
  2912. }
  2913. /// Consider whether capturing the given variable can possibly lead to
  2914. /// a retain cycle.
  2915. static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
  2916. // In ARC, it's captured strongly iff the variable has __strong
  2917. // lifetime. In MRR, it's captured strongly if the variable is
  2918. // __block and has an appropriate type.
  2919. if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  2920. return false;
  2921. owner.Variable = var;
  2922. owner.setLocsFrom(ref);
  2923. return true;
  2924. }
  2925. static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
  2926. while (true) {
  2927. e = e->IgnoreParens();
  2928. if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
  2929. switch (cast->getCastKind()) {
  2930. case CK_BitCast:
  2931. case CK_LValueBitCast:
  2932. case CK_LValueToRValue:
  2933. e = cast->getSubExpr();
  2934. continue;
  2935. case CK_GetObjCProperty: {
  2936. // Bail out if this isn't a strong explicit property.
  2937. const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
  2938. if (pre->isImplicitProperty()) return false;
  2939. ObjCPropertyDecl *property = pre->getExplicitProperty();
  2940. if (!(property->getPropertyAttributes() &
  2941. (ObjCPropertyDecl::OBJC_PR_retain |
  2942. ObjCPropertyDecl::OBJC_PR_copy |
  2943. ObjCPropertyDecl::OBJC_PR_strong)) &&
  2944. !(property->getPropertyIvarDecl() &&
  2945. property->getPropertyIvarDecl()->getType()
  2946. .getObjCLifetime() == Qualifiers::OCL_Strong))
  2947. return false;
  2948. owner.Indirect = true;
  2949. e = const_cast<Expr*>(pre->getBase());
  2950. continue;
  2951. }
  2952. default:
  2953. return false;
  2954. }
  2955. }
  2956. if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
  2957. ObjCIvarDecl *ivar = ref->getDecl();
  2958. if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
  2959. return false;
  2960. // Try to find a retain cycle in the base.
  2961. if (!findRetainCycleOwner(ref->getBase(), owner))
  2962. return false;
  2963. if (ref->isFreeIvar()) owner.setLocsFrom(ref);
  2964. owner.Indirect = true;
  2965. return true;
  2966. }
  2967. if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
  2968. VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
  2969. if (!var) return false;
  2970. return considerVariable(var, ref, owner);
  2971. }
  2972. if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
  2973. owner.Variable = ref->getDecl();
  2974. owner.setLocsFrom(ref);
  2975. return true;
  2976. }
  2977. if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
  2978. if (member->isArrow()) return false;
  2979. // Don't count this as an indirect ownership.
  2980. e = member->getBase();
  2981. continue;
  2982. }
  2983. // Array ivars?
  2984. return false;
  2985. }
  2986. }
  2987. namespace {
  2988. struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
  2989. FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
  2990. : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
  2991. Variable(variable), Capturer(0) {}
  2992. VarDecl *Variable;
  2993. Expr *Capturer;
  2994. void VisitDeclRefExpr(DeclRefExpr *ref) {
  2995. if (ref->getDecl() == Variable && !Capturer)
  2996. Capturer = ref;
  2997. }
  2998. void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
  2999. if (ref->getDecl() == Variable && !Capturer)
  3000. Capturer = ref;
  3001. }
  3002. void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
  3003. if (Capturer) return;
  3004. Visit(ref->getBase());
  3005. if (Capturer && ref->isFreeIvar())
  3006. Capturer = ref;
  3007. }
  3008. void VisitBlockExpr(BlockExpr *block) {
  3009. // Look inside nested blocks
  3010. if (block->getBlockDecl()->capturesVariable(Variable))
  3011. Visit(block->getBlockDecl()->getBody());
  3012. }
  3013. };
  3014. }
  3015. /// Check whether the given argument is a block which captures a
  3016. /// variable.
  3017. static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
  3018. assert(owner.Variable && owner.Loc.isValid());
  3019. e = e->IgnoreParenCasts();
  3020. BlockExpr *block = dyn_cast<BlockExpr>(e);
  3021. if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
  3022. return 0;
  3023. FindCaptureVisitor visitor(S.Context, owner.Variable);
  3024. visitor.Visit(block->getBlockDecl()->getBody());
  3025. return visitor.Capturer;
  3026. }
  3027. static void diagnoseRetainCycle(Sema &S, Expr *capturer,
  3028. RetainCycleOwner &owner) {
  3029. assert(capturer);
  3030. assert(owner.Variable && owner.Loc.isValid());
  3031. S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
  3032. << owner.Variable << capturer->getSourceRange();
  3033. S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
  3034. << owner.Indirect << owner.Range;
  3035. }
  3036. /// Check for a keyword selector that starts with the word 'add' or
  3037. /// 'set'.
  3038. static bool isSetterLikeSelector(Selector sel) {
  3039. if (sel.isUnarySelector()) return false;
  3040. llvm::StringRef str = sel.getNameForSlot(0);
  3041. while (!str.empty() && str.front() == '_') str = str.substr(1);
  3042. if (str.startswith("set") || str.startswith("add"))
  3043. str = str.substr(3);
  3044. else
  3045. return false;
  3046. if (str.empty()) return true;
  3047. return !islower(str.front());
  3048. }
  3049. /// Check a message send to see if it's likely to cause a retain cycle.
  3050. void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
  3051. // Only check instance methods whose selector looks like a setter.
  3052. if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
  3053. return;
  3054. // Try to find a variable that the receiver is strongly owned by.
  3055. RetainCycleOwner owner;
  3056. if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
  3057. if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
  3058. return;
  3059. } else {
  3060. assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
  3061. owner.Variable = getCurMethodDecl()->getSelfDecl();
  3062. owner.Loc = msg->getSuperLoc();
  3063. owner.Range = msg->getSuperLoc();
  3064. }
  3065. // Check whether the receiver is captured by any of the arguments.
  3066. for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
  3067. if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
  3068. return diagnoseRetainCycle(*this, capturer, owner);
  3069. }
  3070. /// Check a property assign to see if it's likely to cause a retain cycle.
  3071. void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
  3072. RetainCycleOwner owner;
  3073. if (!findRetainCycleOwner(receiver, owner))
  3074. return;
  3075. if (Expr *capturer = findCapturingExpr(*this, argument, owner))
  3076. diagnoseRetainCycle(*this, capturer, owner);
  3077. }
  3078. void Sema::checkUnsafeAssigns(SourceLocation Loc,
  3079. QualType LHS, Expr *RHS) {
  3080. Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
  3081. if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
  3082. return;
  3083. if (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS))
  3084. if (cast->getCastKind() == CK_ObjCConsumeObject)
  3085. Diag(Loc, diag::warn_arc_retained_assign)
  3086. << (LT == Qualifiers::OCL_ExplicitNone)
  3087. << RHS->getSourceRange();
  3088. }