]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / tools / clang / lib / Sema / SemaChecking.cpp
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
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Sema.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Analysis/Analyses/FormatString.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/EvaluatedExprVisitor.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "clang/Basic/TargetBuiltins.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include <limits>
39 using namespace clang;
40 using namespace sema;
41
42 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43                                                     unsigned ByteNo) const {
44   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45                                PP.getLangOptions(), PP.getTargetInfo());
46 }
47   
48
49 /// CheckablePrintfAttr - does a function call have a "printf" attribute
50 /// and arguments that merit checking?
51 bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52   if (Format->getType() == "printf") return true;
53   if (Format->getType() == "printf0") {
54     // printf0 allows null "format" string; if so don't check format/args
55     unsigned format_idx = Format->getFormatIdx() - 1;
56     // Does the index refer to the implicit object argument?
57     if (isa<CXXMemberCallExpr>(TheCall)) {
58       if (format_idx == 0)
59         return false;
60       --format_idx;
61     }
62     if (format_idx < TheCall->getNumArgs()) {
63       Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
64       if (!Format->isNullPointerConstant(Context,
65                                          Expr::NPC_ValueDependentIsNull))
66         return true;
67     }
68   }
69   return false;
70 }
71
72 /// Checks that a call expression's argument count is the desired number.
73 /// This is useful when doing custom type-checking.  Returns true on error.
74 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75   unsigned argCount = call->getNumArgs();
76   if (argCount == desiredArgCount) return false;
77
78   if (argCount < desiredArgCount)
79     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80         << 0 /*function call*/ << desiredArgCount << argCount
81         << call->getSourceRange();
82
83   // Highlight all the excess arguments.
84   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85                     call->getArg(argCount - 1)->getLocEnd());
86     
87   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88     << 0 /*function call*/ << desiredArgCount << argCount
89     << call->getArg(1)->getSourceRange();
90 }
91
92 /// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93 /// annotation is a non wide string literal.
94 static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95   Arg = Arg->IgnoreParenCasts();
96   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97   if (!Literal || !Literal->isAscii()) {
98     S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99       << Arg->getSourceRange();
100     return true;
101   }
102   return false;
103 }
104
105 ExprResult
106 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
107   ExprResult TheCallResult(Owned(TheCall));
108
109   // Find out if any arguments are required to be integer constant expressions.
110   unsigned ICEArguments = 0;
111   ASTContext::GetBuiltinTypeError Error;
112   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113   if (Error != ASTContext::GE_None)
114     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
115   
116   // If any arguments are required to be ICE's, check and diagnose.
117   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118     // Skip arguments not required to be ICE's.
119     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120     
121     llvm::APSInt Result;
122     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123       return true;
124     ICEArguments &= ~(1 << ArgNo);
125   }
126   
127   switch (BuiltinID) {
128   case Builtin::BI__builtin___CFStringMakeConstantString:
129     assert(TheCall->getNumArgs() == 1 &&
130            "Wrong # arguments to builtin CFStringMakeConstantString");
131     if (CheckObjCString(TheCall->getArg(0)))
132       return ExprError();
133     break;
134   case Builtin::BI__builtin_stdarg_start:
135   case Builtin::BI__builtin_va_start:
136     if (SemaBuiltinVAStart(TheCall))
137       return ExprError();
138     break;
139   case Builtin::BI__builtin_isgreater:
140   case Builtin::BI__builtin_isgreaterequal:
141   case Builtin::BI__builtin_isless:
142   case Builtin::BI__builtin_islessequal:
143   case Builtin::BI__builtin_islessgreater:
144   case Builtin::BI__builtin_isunordered:
145     if (SemaBuiltinUnorderedCompare(TheCall))
146       return ExprError();
147     break;
148   case Builtin::BI__builtin_fpclassify:
149     if (SemaBuiltinFPClassification(TheCall, 6))
150       return ExprError();
151     break;
152   case Builtin::BI__builtin_isfinite:
153   case Builtin::BI__builtin_isinf:
154   case Builtin::BI__builtin_isinf_sign:
155   case Builtin::BI__builtin_isnan:
156   case Builtin::BI__builtin_isnormal:
157     if (SemaBuiltinFPClassification(TheCall, 1))
158       return ExprError();
159     break;
160   case Builtin::BI__builtin_shufflevector:
161     return SemaBuiltinShuffleVector(TheCall);
162     // TheCall will be freed by the smart pointer here, but that's fine, since
163     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
164   case Builtin::BI__builtin_prefetch:
165     if (SemaBuiltinPrefetch(TheCall))
166       return ExprError();
167     break;
168   case Builtin::BI__builtin_object_size:
169     if (SemaBuiltinObjectSize(TheCall))
170       return ExprError();
171     break;
172   case Builtin::BI__builtin_longjmp:
173     if (SemaBuiltinLongjmp(TheCall))
174       return ExprError();
175     break;
176
177   case Builtin::BI__builtin_classify_type:
178     if (checkArgCount(*this, TheCall, 1)) return true;
179     TheCall->setType(Context.IntTy);
180     break;
181   case Builtin::BI__builtin_constant_p:
182     if (checkArgCount(*this, TheCall, 1)) return true;
183     TheCall->setType(Context.IntTy);
184     break;
185   case Builtin::BI__sync_fetch_and_add:
186   case Builtin::BI__sync_fetch_and_sub:
187   case Builtin::BI__sync_fetch_and_or:
188   case Builtin::BI__sync_fetch_and_and:
189   case Builtin::BI__sync_fetch_and_xor:
190   case Builtin::BI__sync_add_and_fetch:
191   case Builtin::BI__sync_sub_and_fetch:
192   case Builtin::BI__sync_and_and_fetch:
193   case Builtin::BI__sync_or_and_fetch:
194   case Builtin::BI__sync_xor_and_fetch:
195   case Builtin::BI__sync_val_compare_and_swap:
196   case Builtin::BI__sync_bool_compare_and_swap:
197   case Builtin::BI__sync_lock_test_and_set:
198   case Builtin::BI__sync_lock_release:
199   case Builtin::BI__sync_swap:
200     return SemaBuiltinAtomicOverloaded(move(TheCallResult));
201   case Builtin::BI__atomic_load:
202     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203   case Builtin::BI__atomic_store:
204     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205   case Builtin::BI__atomic_exchange:
206     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207   case Builtin::BI__atomic_compare_exchange_strong:
208     return SemaAtomicOpsOverloaded(move(TheCallResult),
209                                    AtomicExpr::CmpXchgStrong);
210   case Builtin::BI__atomic_compare_exchange_weak:
211     return SemaAtomicOpsOverloaded(move(TheCallResult),
212                                    AtomicExpr::CmpXchgWeak);
213   case Builtin::BI__atomic_fetch_add:
214     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215   case Builtin::BI__atomic_fetch_sub:
216     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217   case Builtin::BI__atomic_fetch_and:
218     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219   case Builtin::BI__atomic_fetch_or:
220     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221   case Builtin::BI__atomic_fetch_xor:
222     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
223   case Builtin::BI__builtin_annotation:
224     if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225       return ExprError();
226     break;
227   }
228   
229   // Since the target specific builtins for each arch overlap, only check those
230   // of the arch we are compiling for.
231   if (BuiltinID >= Builtin::FirstTSBuiltin) {
232     switch (Context.getTargetInfo().getTriple().getArch()) {
233       case llvm::Triple::arm:
234       case llvm::Triple::thumb:
235         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236           return ExprError();
237         break;
238       default:
239         break;
240     }
241   }
242
243   return move(TheCallResult);
244 }
245
246 // Get the valid immediate range for the specified NEON type code.
247 static unsigned RFT(unsigned t, bool shift = false) {
248   bool quad = t & 0x10;
249   
250   switch (t & 0x7) {
251     case 0: // i8
252       return shift ? 7 : (8 << (int)quad) - 1;
253     case 1: // i16
254       return shift ? 15 : (4 << (int)quad) - 1;
255     case 2: // i32
256       return shift ? 31 : (2 << (int)quad) - 1;
257     case 3: // i64
258       return shift ? 63 : (1 << (int)quad) - 1;
259     case 4: // f32
260       assert(!shift && "cannot shift float types!");
261       return (2 << (int)quad) - 1;
262     case 5: // poly8
263       return shift ? 7 : (8 << (int)quad) - 1;
264     case 6: // poly16
265       return shift ? 15 : (4 << (int)quad) - 1;
266     case 7: // float16
267       assert(!shift && "cannot shift float types!");
268       return (4 << (int)quad) - 1;
269   }
270   return 0;
271 }
272
273 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
274   llvm::APSInt Result;
275
276   unsigned mask = 0;
277   unsigned TV = 0;
278   switch (BuiltinID) {
279 #define GET_NEON_OVERLOAD_CHECK
280 #include "clang/Basic/arm_neon.inc"
281 #undef GET_NEON_OVERLOAD_CHECK
282   }
283   
284   // For NEON intrinsics which are overloaded on vector element type, validate
285   // the immediate which specifies which variant to emit.
286   if (mask) {
287     unsigned ArgNo = TheCall->getNumArgs()-1;
288     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
289       return true;
290     
291     TV = Result.getLimitedValue(32);
292     if ((TV > 31) || (mask & (1 << TV)) == 0)
293       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
294         << TheCall->getArg(ArgNo)->getSourceRange();
295   }
296   
297   // For NEON intrinsics which take an immediate value as part of the 
298   // instruction, range check them here.
299   unsigned i = 0, l = 0, u = 0;
300   switch (BuiltinID) {
301   default: return false;
302   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
303   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
304   case ARM::BI__builtin_arm_vcvtr_f:
305   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
306 #define GET_NEON_IMMEDIATE_CHECK
307 #include "clang/Basic/arm_neon.inc"
308 #undef GET_NEON_IMMEDIATE_CHECK
309   };
310
311   // Check that the immediate argument is actually a constant.
312   if (SemaBuiltinConstantArg(TheCall, i, Result))
313     return true;
314
315   // Range check against the upper/lower values for this isntruction.
316   unsigned Val = Result.getZExtValue();
317   if (Val < l || Val > (u + l))
318     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
319       << l << u+l << TheCall->getArg(i)->getSourceRange();
320
321   // FIXME: VFP Intrinsics should error if VFP not present.
322   return false;
323 }
324
325 /// CheckFunctionCall - Check a direct function call for various correctness
326 /// and safety properties not strictly enforced by the C type system.
327 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
328   // Get the IdentifierInfo* for the called function.
329   IdentifierInfo *FnInfo = FDecl->getIdentifier();
330
331   // None of the checks below are needed for functions that don't have
332   // simple names (e.g., C++ conversion functions).
333   if (!FnInfo)
334     return false;
335
336   // FIXME: This mechanism should be abstracted to be less fragile and
337   // more efficient. For example, just map function ids to custom
338   // handlers.
339
340   // Printf and scanf checking.
341   for (specific_attr_iterator<FormatAttr>
342          i = FDecl->specific_attr_begin<FormatAttr>(),
343          e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
344
345     const FormatAttr *Format = *i;
346     const bool b = Format->getType() == "scanf";
347     if (b || CheckablePrintfAttr(Format, TheCall)) {
348       bool HasVAListArg = Format->getFirstArg() == 0;
349       CheckPrintfScanfArguments(TheCall, HasVAListArg,
350                                 Format->getFormatIdx() - 1,
351                                 HasVAListArg ? 0 : Format->getFirstArg() - 1,
352                                 !b);
353     }
354   }
355
356   for (specific_attr_iterator<NonNullAttr>
357          i = FDecl->specific_attr_begin<NonNullAttr>(),
358          e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
359     CheckNonNullArguments(*i, TheCall->getArgs(),
360                           TheCall->getCallee()->getLocStart());
361   }
362
363   // Builtin handling
364   int CMF = -1;
365   switch (FDecl->getBuiltinID()) {
366   case Builtin::BI__builtin_memset:
367   case Builtin::BI__builtin___memset_chk:
368   case Builtin::BImemset:
369     CMF = CMF_Memset;
370     break;
371     
372   case Builtin::BI__builtin_memcpy:
373   case Builtin::BI__builtin___memcpy_chk:
374   case Builtin::BImemcpy:
375     CMF = CMF_Memcpy;
376     break;
377     
378   case Builtin::BI__builtin_memmove:
379   case Builtin::BI__builtin___memmove_chk:
380   case Builtin::BImemmove:
381     CMF = CMF_Memmove;
382     break;
383
384   case Builtin::BIstrlcpy:
385   case Builtin::BIstrlcat:
386     CheckStrlcpycatArguments(TheCall, FnInfo);
387     break;
388     
389   case Builtin::BI__builtin_memcmp:
390     CMF = CMF_Memcmp;
391     break;
392     
393   case Builtin::BI__builtin_strncpy:
394   case Builtin::BI__builtin___strncpy_chk:
395   case Builtin::BIstrncpy:
396     CMF = CMF_Strncpy;
397     break;
398
399   case Builtin::BI__builtin_strncmp:
400     CMF = CMF_Strncmp;
401     break;
402
403   case Builtin::BI__builtin_strncasecmp:
404     CMF = CMF_Strncasecmp;
405     break;
406
407   case Builtin::BI__builtin_strncat:
408   case Builtin::BIstrncat:
409     CMF = CMF_Strncat;
410     break;
411
412   case Builtin::BI__builtin_strndup:
413   case Builtin::BIstrndup:
414     CMF = CMF_Strndup;
415     break;
416
417   default:
418     if (FDecl->getLinkage() == ExternalLinkage &&
419         (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
420       if (FnInfo->isStr("memset"))
421         CMF = CMF_Memset;
422       else if (FnInfo->isStr("memcpy"))
423         CMF = CMF_Memcpy;
424       else if (FnInfo->isStr("memmove"))
425         CMF = CMF_Memmove;
426       else if (FnInfo->isStr("memcmp"))
427         CMF = CMF_Memcmp;
428       else if (FnInfo->isStr("strncpy"))
429         CMF = CMF_Strncpy;
430       else if (FnInfo->isStr("strncmp"))
431         CMF = CMF_Strncmp;
432       else if (FnInfo->isStr("strncasecmp"))
433         CMF = CMF_Strncasecmp;
434       else if (FnInfo->isStr("strncat"))
435         CMF = CMF_Strncat;
436       else if (FnInfo->isStr("strndup"))
437         CMF = CMF_Strndup;
438     }
439     break;
440   }
441    
442   // Memset/memcpy/memmove handling
443   if (CMF != -1)
444     CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
445
446   return false;
447 }
448
449 bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
450   // Printf checking.
451   const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
452   if (!Format)
453     return false;
454
455   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
456   if (!V)
457     return false;
458
459   QualType Ty = V->getType();
460   if (!Ty->isBlockPointerType())
461     return false;
462
463   const bool b = Format->getType() == "scanf";
464   if (!b && !CheckablePrintfAttr(Format, TheCall))
465     return false;
466
467   bool HasVAListArg = Format->getFirstArg() == 0;
468   CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
469                             HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
470
471   return false;
472 }
473
474 ExprResult
475 Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
476   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
477   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
478
479   // All these operations take one of the following four forms:
480   // T   __atomic_load(_Atomic(T)*, int)                              (loads)
481   // T*  __atomic_add(_Atomic(T*)*, ptrdiff_t, int)         (pointer add/sub)
482   // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
483   //                                                                (cmpxchg)
484   // T   __atomic_exchange(_Atomic(T)*, T, int)             (everything else)
485   // where T is an appropriate type, and the int paremeterss are for orderings.
486   unsigned NumVals = 1;
487   unsigned NumOrders = 1;
488   if (Op == AtomicExpr::Load) {
489     NumVals = 0;
490   } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
491     NumVals = 2;
492     NumOrders = 2;
493   }
494
495   if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
496     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
497       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
498       << TheCall->getCallee()->getSourceRange();
499     return ExprError();
500   } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
501     Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
502          diag::err_typecheck_call_too_many_args)
503       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
504       << TheCall->getCallee()->getSourceRange();
505     return ExprError();
506   }
507
508   // Inspect the first argument of the atomic operation.  This should always be
509   // a pointer to an _Atomic type.
510   Expr *Ptr = TheCall->getArg(0);
511   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
512   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
513   if (!pointerType) {
514     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
515       << Ptr->getType() << Ptr->getSourceRange();
516     return ExprError();
517   }
518
519   QualType AtomTy = pointerType->getPointeeType();
520   if (!AtomTy->isAtomicType()) {
521     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
522       << Ptr->getType() << Ptr->getSourceRange();
523     return ExprError();
524   }
525   QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
526
527   if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
528       !ValType->isIntegerType() && !ValType->isPointerType()) {
529     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
530       << Ptr->getType() << Ptr->getSourceRange();
531     return ExprError();
532   }
533
534   if (!ValType->isIntegerType() &&
535       (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
536     Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
537       << Ptr->getType() << Ptr->getSourceRange();
538     return ExprError();
539   }
540
541   switch (ValType.getObjCLifetime()) {
542   case Qualifiers::OCL_None:
543   case Qualifiers::OCL_ExplicitNone:
544     // okay
545     break;
546
547   case Qualifiers::OCL_Weak:
548   case Qualifiers::OCL_Strong:
549   case Qualifiers::OCL_Autoreleasing:
550     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
551       << ValType << Ptr->getSourceRange();
552     return ExprError();
553   }
554
555   QualType ResultType = ValType;
556   if (Op == AtomicExpr::Store)
557     ResultType = Context.VoidTy;
558   else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
559     ResultType = Context.BoolTy;
560
561   // The first argument --- the pointer --- has a fixed type; we
562   // deduce the types of the rest of the arguments accordingly.  Walk
563   // the remaining arguments, converting them to the deduced value type.
564   for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
565     ExprResult Arg = TheCall->getArg(i);
566     QualType Ty;
567     if (i < NumVals+1) {
568       // The second argument to a cmpxchg is a pointer to the data which will
569       // be exchanged. The second argument to a pointer add/subtract is the
570       // amount to add/subtract, which must be a ptrdiff_t.  The third
571       // argument to a cmpxchg and the second argument in all other cases
572       // is the type of the value.
573       if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
574                      Op == AtomicExpr::CmpXchgStrong))
575          Ty = Context.getPointerType(ValType.getUnqualifiedType());
576       else if (!ValType->isIntegerType() &&
577                (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
578         Ty = Context.getPointerDiffType();
579       else
580         Ty = ValType;
581     } else {
582       // The order(s) are always converted to int.
583       Ty = Context.IntTy;
584     }
585     InitializedEntity Entity =
586         InitializedEntity::InitializeParameter(Context, Ty, false);
587     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
588     if (Arg.isInvalid())
589       return true;
590     TheCall->setArg(i, Arg.get());
591   }
592
593   SmallVector<Expr*, 5> SubExprs;
594   SubExprs.push_back(Ptr);
595   if (Op == AtomicExpr::Load) {
596     SubExprs.push_back(TheCall->getArg(1)); // Order
597   } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
598     SubExprs.push_back(TheCall->getArg(2)); // Order
599     SubExprs.push_back(TheCall->getArg(1)); // Val1
600   } else {
601     SubExprs.push_back(TheCall->getArg(3)); // Order
602     SubExprs.push_back(TheCall->getArg(1)); // Val1
603     SubExprs.push_back(TheCall->getArg(2)); // Val2
604     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
605   }
606
607   return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
608                                         SubExprs.data(), SubExprs.size(),
609                                         ResultType, Op,
610                                         TheCall->getRParenLoc()));
611 }
612
613
614 /// checkBuiltinArgument - Given a call to a builtin function, perform
615 /// normal type-checking on the given argument, updating the call in
616 /// place.  This is useful when a builtin function requires custom
617 /// type-checking for some of its arguments but not necessarily all of
618 /// them.
619 ///
620 /// Returns true on error.
621 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
622   FunctionDecl *Fn = E->getDirectCallee();
623   assert(Fn && "builtin call without direct callee!");
624
625   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
626   InitializedEntity Entity =
627     InitializedEntity::InitializeParameter(S.Context, Param);
628
629   ExprResult Arg = E->getArg(0);
630   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
631   if (Arg.isInvalid())
632     return true;
633
634   E->setArg(ArgIndex, Arg.take());
635   return false;
636 }
637
638 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
639 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
640 /// type of its first argument.  The main ActOnCallExpr routines have already
641 /// promoted the types of arguments because all of these calls are prototyped as
642 /// void(...).
643 ///
644 /// This function goes through and does final semantic checking for these
645 /// builtins,
646 ExprResult
647 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
648   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
649   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
650   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
651
652   // Ensure that we have at least one argument to do type inference from.
653   if (TheCall->getNumArgs() < 1) {
654     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
655       << 0 << 1 << TheCall->getNumArgs()
656       << TheCall->getCallee()->getSourceRange();
657     return ExprError();
658   }
659
660   // Inspect the first argument of the atomic builtin.  This should always be
661   // a pointer type, whose element is an integral scalar or pointer type.
662   // Because it is a pointer type, we don't have to worry about any implicit
663   // casts here.
664   // FIXME: We don't allow floating point scalars as input.
665   Expr *FirstArg = TheCall->getArg(0);
666   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
667   if (!pointerType) {
668     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
669       << FirstArg->getType() << FirstArg->getSourceRange();
670     return ExprError();
671   }
672
673   QualType ValType = pointerType->getPointeeType();
674   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
675       !ValType->isBlockPointerType()) {
676     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
677       << FirstArg->getType() << FirstArg->getSourceRange();
678     return ExprError();
679   }
680
681   switch (ValType.getObjCLifetime()) {
682   case Qualifiers::OCL_None:
683   case Qualifiers::OCL_ExplicitNone:
684     // okay
685     break;
686
687   case Qualifiers::OCL_Weak:
688   case Qualifiers::OCL_Strong:
689   case Qualifiers::OCL_Autoreleasing:
690     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
691       << ValType << FirstArg->getSourceRange();
692     return ExprError();
693   }
694
695   // Strip any qualifiers off ValType.
696   ValType = ValType.getUnqualifiedType();
697
698   // The majority of builtins return a value, but a few have special return
699   // types, so allow them to override appropriately below.
700   QualType ResultType = ValType;
701
702   // We need to figure out which concrete builtin this maps onto.  For example,
703   // __sync_fetch_and_add with a 2 byte object turns into
704   // __sync_fetch_and_add_2.
705 #define BUILTIN_ROW(x) \
706   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
707     Builtin::BI##x##_8, Builtin::BI##x##_16 }
708
709   static const unsigned BuiltinIndices[][5] = {
710     BUILTIN_ROW(__sync_fetch_and_add),
711     BUILTIN_ROW(__sync_fetch_and_sub),
712     BUILTIN_ROW(__sync_fetch_and_or),
713     BUILTIN_ROW(__sync_fetch_and_and),
714     BUILTIN_ROW(__sync_fetch_and_xor),
715
716     BUILTIN_ROW(__sync_add_and_fetch),
717     BUILTIN_ROW(__sync_sub_and_fetch),
718     BUILTIN_ROW(__sync_and_and_fetch),
719     BUILTIN_ROW(__sync_or_and_fetch),
720     BUILTIN_ROW(__sync_xor_and_fetch),
721
722     BUILTIN_ROW(__sync_val_compare_and_swap),
723     BUILTIN_ROW(__sync_bool_compare_and_swap),
724     BUILTIN_ROW(__sync_lock_test_and_set),
725     BUILTIN_ROW(__sync_lock_release),
726     BUILTIN_ROW(__sync_swap)
727   };
728 #undef BUILTIN_ROW
729
730   // Determine the index of the size.
731   unsigned SizeIndex;
732   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
733   case 1: SizeIndex = 0; break;
734   case 2: SizeIndex = 1; break;
735   case 4: SizeIndex = 2; break;
736   case 8: SizeIndex = 3; break;
737   case 16: SizeIndex = 4; break;
738   default:
739     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
740       << FirstArg->getType() << FirstArg->getSourceRange();
741     return ExprError();
742   }
743
744   // Each of these builtins has one pointer argument, followed by some number of
745   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
746   // that we ignore.  Find out which row of BuiltinIndices to read from as well
747   // as the number of fixed args.
748   unsigned BuiltinID = FDecl->getBuiltinID();
749   unsigned BuiltinIndex, NumFixed = 1;
750   switch (BuiltinID) {
751   default: llvm_unreachable("Unknown overloaded atomic builtin!");
752   case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
753   case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
754   case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
755   case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
756   case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
757
758   case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
759   case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
760   case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
761   case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
762   case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
763
764   case Builtin::BI__sync_val_compare_and_swap:
765     BuiltinIndex = 10;
766     NumFixed = 2;
767     break;
768   case Builtin::BI__sync_bool_compare_and_swap:
769     BuiltinIndex = 11;
770     NumFixed = 2;
771     ResultType = Context.BoolTy;
772     break;
773   case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
774   case Builtin::BI__sync_lock_release:
775     BuiltinIndex = 13;
776     NumFixed = 0;
777     ResultType = Context.VoidTy;
778     break;
779   case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
780   }
781
782   // Now that we know how many fixed arguments we expect, first check that we
783   // have at least that many.
784   if (TheCall->getNumArgs() < 1+NumFixed) {
785     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
786       << 0 << 1+NumFixed << TheCall->getNumArgs()
787       << TheCall->getCallee()->getSourceRange();
788     return ExprError();
789   }
790
791   // Get the decl for the concrete builtin from this, we can tell what the
792   // concrete integer type we should convert to is.
793   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
794   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
795   IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
796   FunctionDecl *NewBuiltinDecl =
797     cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
798                                            TUScope, false, DRE->getLocStart()));
799
800   // The first argument --- the pointer --- has a fixed type; we
801   // deduce the types of the rest of the arguments accordingly.  Walk
802   // the remaining arguments, converting them to the deduced value type.
803   for (unsigned i = 0; i != NumFixed; ++i) {
804     ExprResult Arg = TheCall->getArg(i+1);
805
806     // If the argument is an implicit cast, then there was a promotion due to
807     // "...", just remove it now.
808     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
809       Arg = ICE->getSubExpr();
810       ICE->setSubExpr(0);
811       TheCall->setArg(i+1, Arg.get());
812     }
813
814     // GCC does an implicit conversion to the pointer or integer ValType.  This
815     // can fail in some cases (1i -> int**), check for this error case now.
816     // Initialize the argument.
817     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
818                                                    ValType, /*consume*/ false);
819     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
820     if (Arg.isInvalid())
821       return ExprError();
822
823     // Okay, we have something that *can* be converted to the right type.  Check
824     // to see if there is a potentially weird extension going on here.  This can
825     // happen when you do an atomic operation on something like an char* and
826     // pass in 42.  The 42 gets converted to char.  This is even more strange
827     // for things like 45.123 -> char, etc.
828     // FIXME: Do this check.
829     TheCall->setArg(i+1, Arg.take());
830   }
831
832   ASTContext& Context = this->getASTContext();
833
834   // Create a new DeclRefExpr to refer to the new decl.
835   DeclRefExpr* NewDRE = DeclRefExpr::Create(
836       Context,
837       DRE->getQualifierLoc(),
838       NewBuiltinDecl,
839       DRE->getLocation(),
840       NewBuiltinDecl->getType(),
841       DRE->getValueKind());
842
843   // Set the callee in the CallExpr.
844   // FIXME: This leaks the original parens and implicit casts.
845   ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
846   if (PromotedCall.isInvalid())
847     return ExprError();
848   TheCall->setCallee(PromotedCall.take());
849
850   // Change the result type of the call to match the original value type. This
851   // is arbitrary, but the codegen for these builtins ins design to handle it
852   // gracefully.
853   TheCall->setType(ResultType);
854
855   return move(TheCallResult);
856 }
857
858 /// CheckObjCString - Checks that the argument to the builtin
859 /// CFString constructor is correct
860 /// Note: It might also make sense to do the UTF-16 conversion here (would
861 /// simplify the backend).
862 bool Sema::CheckObjCString(Expr *Arg) {
863   Arg = Arg->IgnoreParenCasts();
864   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
865
866   if (!Literal || !Literal->isAscii()) {
867     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
868       << Arg->getSourceRange();
869     return true;
870   }
871
872   if (Literal->containsNonAsciiOrNull()) {
873     StringRef String = Literal->getString();
874     unsigned NumBytes = String.size();
875     SmallVector<UTF16, 128> ToBuf(NumBytes);
876     const UTF8 *FromPtr = (UTF8 *)String.data();
877     UTF16 *ToPtr = &ToBuf[0];
878     
879     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
880                                                  &ToPtr, ToPtr + NumBytes,
881                                                  strictConversion);
882     // Check for conversion failure.
883     if (Result != conversionOK)
884       Diag(Arg->getLocStart(),
885            diag::warn_cfstring_truncated) << Arg->getSourceRange();
886   }
887   return false;
888 }
889
890 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
891 /// Emit an error and return true on failure, return false on success.
892 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
893   Expr *Fn = TheCall->getCallee();
894   if (TheCall->getNumArgs() > 2) {
895     Diag(TheCall->getArg(2)->getLocStart(),
896          diag::err_typecheck_call_too_many_args)
897       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
898       << Fn->getSourceRange()
899       << SourceRange(TheCall->getArg(2)->getLocStart(),
900                      (*(TheCall->arg_end()-1))->getLocEnd());
901     return true;
902   }
903
904   if (TheCall->getNumArgs() < 2) {
905     return Diag(TheCall->getLocEnd(),
906       diag::err_typecheck_call_too_few_args_at_least)
907       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
908   }
909
910   // Type-check the first argument normally.
911   if (checkBuiltinArgument(*this, TheCall, 0))
912     return true;
913
914   // Determine whether the current function is variadic or not.
915   BlockScopeInfo *CurBlock = getCurBlock();
916   bool isVariadic;
917   if (CurBlock)
918     isVariadic = CurBlock->TheDecl->isVariadic();
919   else if (FunctionDecl *FD = getCurFunctionDecl())
920     isVariadic = FD->isVariadic();
921   else
922     isVariadic = getCurMethodDecl()->isVariadic();
923
924   if (!isVariadic) {
925     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
926     return true;
927   }
928
929   // Verify that the second argument to the builtin is the last argument of the
930   // current function or method.
931   bool SecondArgIsLastNamedArgument = false;
932   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
933
934   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
935     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
936       // FIXME: This isn't correct for methods (results in bogus warning).
937       // Get the last formal in the current function.
938       const ParmVarDecl *LastArg;
939       if (CurBlock)
940         LastArg = *(CurBlock->TheDecl->param_end()-1);
941       else if (FunctionDecl *FD = getCurFunctionDecl())
942         LastArg = *(FD->param_end()-1);
943       else
944         LastArg = *(getCurMethodDecl()->param_end()-1);
945       SecondArgIsLastNamedArgument = PV == LastArg;
946     }
947   }
948
949   if (!SecondArgIsLastNamedArgument)
950     Diag(TheCall->getArg(1)->getLocStart(),
951          diag::warn_second_parameter_of_va_start_not_last_named_argument);
952   return false;
953 }
954
955 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
956 /// friends.  This is declared to take (...), so we have to check everything.
957 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
958   if (TheCall->getNumArgs() < 2)
959     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
960       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
961   if (TheCall->getNumArgs() > 2)
962     return Diag(TheCall->getArg(2)->getLocStart(),
963                 diag::err_typecheck_call_too_many_args)
964       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
965       << SourceRange(TheCall->getArg(2)->getLocStart(),
966                      (*(TheCall->arg_end()-1))->getLocEnd());
967
968   ExprResult OrigArg0 = TheCall->getArg(0);
969   ExprResult OrigArg1 = TheCall->getArg(1);
970
971   // Do standard promotions between the two arguments, returning their common
972   // type.
973   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
974   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
975     return true;
976
977   // Make sure any conversions are pushed back into the call; this is
978   // type safe since unordered compare builtins are declared as "_Bool
979   // foo(...)".
980   TheCall->setArg(0, OrigArg0.get());
981   TheCall->setArg(1, OrigArg1.get());
982
983   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
984     return false;
985
986   // If the common type isn't a real floating type, then the arguments were
987   // invalid for this operation.
988   if (!Res->isRealFloatingType())
989     return Diag(OrigArg0.get()->getLocStart(),
990                 diag::err_typecheck_call_invalid_ordered_compare)
991       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
992       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
993
994   return false;
995 }
996
997 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
998 /// __builtin_isnan and friends.  This is declared to take (...), so we have
999 /// to check everything. We expect the last argument to be a floating point
1000 /// value.
1001 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1002   if (TheCall->getNumArgs() < NumArgs)
1003     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1004       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1005   if (TheCall->getNumArgs() > NumArgs)
1006     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1007                 diag::err_typecheck_call_too_many_args)
1008       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1009       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1010                      (*(TheCall->arg_end()-1))->getLocEnd());
1011
1012   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1013
1014   if (OrigArg->isTypeDependent())
1015     return false;
1016
1017   // This operation requires a non-_Complex floating-point number.
1018   if (!OrigArg->getType()->isRealFloatingType())
1019     return Diag(OrigArg->getLocStart(),
1020                 diag::err_typecheck_call_invalid_unary_fp)
1021       << OrigArg->getType() << OrigArg->getSourceRange();
1022
1023   // If this is an implicit conversion from float -> double, remove it.
1024   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1025     Expr *CastArg = Cast->getSubExpr();
1026     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1027       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1028              "promotion from float to double is the only expected cast here");
1029       Cast->setSubExpr(0);
1030       TheCall->setArg(NumArgs-1, CastArg);
1031       OrigArg = CastArg;
1032     }
1033   }
1034   
1035   return false;
1036 }
1037
1038 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1039 // This is declared to take (...), so we have to check everything.
1040 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1041   if (TheCall->getNumArgs() < 2)
1042     return ExprError(Diag(TheCall->getLocEnd(),
1043                           diag::err_typecheck_call_too_few_args_at_least)
1044       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1045       << TheCall->getSourceRange());
1046
1047   // Determine which of the following types of shufflevector we're checking:
1048   // 1) unary, vector mask: (lhs, mask)
1049   // 2) binary, vector mask: (lhs, rhs, mask)
1050   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1051   QualType resType = TheCall->getArg(0)->getType();
1052   unsigned numElements = 0;
1053   
1054   if (!TheCall->getArg(0)->isTypeDependent() &&
1055       !TheCall->getArg(1)->isTypeDependent()) {
1056     QualType LHSType = TheCall->getArg(0)->getType();
1057     QualType RHSType = TheCall->getArg(1)->getType();
1058     
1059     if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1060       Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1061         << SourceRange(TheCall->getArg(0)->getLocStart(),
1062                        TheCall->getArg(1)->getLocEnd());
1063       return ExprError();
1064     }
1065     
1066     numElements = LHSType->getAs<VectorType>()->getNumElements();
1067     unsigned numResElements = TheCall->getNumArgs() - 2;
1068
1069     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1070     // with mask.  If so, verify that RHS is an integer vector type with the
1071     // same number of elts as lhs.
1072     if (TheCall->getNumArgs() == 2) {
1073       if (!RHSType->hasIntegerRepresentation() || 
1074           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1075         Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1076           << SourceRange(TheCall->getArg(1)->getLocStart(),
1077                          TheCall->getArg(1)->getLocEnd());
1078       numResElements = numElements;
1079     }
1080     else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1081       Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1082         << SourceRange(TheCall->getArg(0)->getLocStart(),
1083                        TheCall->getArg(1)->getLocEnd());
1084       return ExprError();
1085     } else if (numElements != numResElements) {
1086       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1087       resType = Context.getVectorType(eltType, numResElements,
1088                                       VectorType::GenericVector);
1089     }
1090   }
1091
1092   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1093     if (TheCall->getArg(i)->isTypeDependent() ||
1094         TheCall->getArg(i)->isValueDependent())
1095       continue;
1096
1097     llvm::APSInt Result(32);
1098     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1099       return ExprError(Diag(TheCall->getLocStart(),
1100                   diag::err_shufflevector_nonconstant_argument)
1101                 << TheCall->getArg(i)->getSourceRange());
1102
1103     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1104       return ExprError(Diag(TheCall->getLocStart(),
1105                   diag::err_shufflevector_argument_too_large)
1106                << TheCall->getArg(i)->getSourceRange());
1107   }
1108
1109   SmallVector<Expr*, 32> exprs;
1110
1111   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1112     exprs.push_back(TheCall->getArg(i));
1113     TheCall->setArg(i, 0);
1114   }
1115
1116   return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
1117                                             exprs.size(), resType,
1118                                             TheCall->getCallee()->getLocStart(),
1119                                             TheCall->getRParenLoc()));
1120 }
1121
1122 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1123 // This is declared to take (const void*, ...) and can take two
1124 // optional constant int args.
1125 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1126   unsigned NumArgs = TheCall->getNumArgs();
1127
1128   if (NumArgs > 3)
1129     return Diag(TheCall->getLocEnd(),
1130              diag::err_typecheck_call_too_many_args_at_most)
1131              << 0 /*function call*/ << 3 << NumArgs
1132              << TheCall->getSourceRange();
1133
1134   // Argument 0 is checked for us and the remaining arguments must be
1135   // constant integers.
1136   for (unsigned i = 1; i != NumArgs; ++i) {
1137     Expr *Arg = TheCall->getArg(i);
1138     
1139     llvm::APSInt Result;
1140     if (SemaBuiltinConstantArg(TheCall, i, Result))
1141       return true;
1142
1143     // FIXME: gcc issues a warning and rewrites these to 0. These
1144     // seems especially odd for the third argument since the default
1145     // is 3.
1146     if (i == 1) {
1147       if (Result.getLimitedValue() > 1)
1148         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1149              << "0" << "1" << Arg->getSourceRange();
1150     } else {
1151       if (Result.getLimitedValue() > 3)
1152         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1153             << "0" << "3" << Arg->getSourceRange();
1154     }
1155   }
1156
1157   return false;
1158 }
1159
1160 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1161 /// TheCall is a constant expression.
1162 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1163                                   llvm::APSInt &Result) {
1164   Expr *Arg = TheCall->getArg(ArgNum);
1165   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1166   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1167   
1168   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1169   
1170   if (!Arg->isIntegerConstantExpr(Result, Context))
1171     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1172                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1173   
1174   return false;
1175 }
1176
1177 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1178 /// int type). This simply type checks that type is one of the defined
1179 /// constants (0-3).
1180 // For compatibility check 0-3, llvm only handles 0 and 2.
1181 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1182   llvm::APSInt Result;
1183   
1184   // Check constant-ness first.
1185   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1186     return true;
1187
1188   Expr *Arg = TheCall->getArg(1);
1189   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1190     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1191              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1192   }
1193
1194   return false;
1195 }
1196
1197 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1198 /// This checks that val is a constant 1.
1199 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1200   Expr *Arg = TheCall->getArg(1);
1201   llvm::APSInt Result;
1202
1203   // TODO: This is less than ideal. Overload this to take a value.
1204   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1205     return true;
1206   
1207   if (Result != 1)
1208     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1209              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1210
1211   return false;
1212 }
1213
1214 // Handle i > 1 ? "x" : "y", recursively.
1215 bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1216                                   bool HasVAListArg,
1217                                   unsigned format_idx, unsigned firstDataArg,
1218                                   bool isPrintf) {
1219  tryAgain:
1220   if (E->isTypeDependent() || E->isValueDependent())
1221     return false;
1222
1223   E = E->IgnoreParens();
1224
1225   switch (E->getStmtClass()) {
1226   case Stmt::BinaryConditionalOperatorClass:
1227   case Stmt::ConditionalOperatorClass: {
1228     const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
1229     return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1230                                   format_idx, firstDataArg, isPrintf)
1231         && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
1232                                   format_idx, firstDataArg, isPrintf);
1233   }
1234
1235   case Stmt::IntegerLiteralClass:
1236     // Technically -Wformat-nonliteral does not warn about this case.
1237     // The behavior of printf and friends in this case is implementation
1238     // dependent.  Ideally if the format string cannot be null then
1239     // it should have a 'nonnull' attribute in the function prototype.
1240     return true;
1241
1242   case Stmt::ImplicitCastExprClass: {
1243     E = cast<ImplicitCastExpr>(E)->getSubExpr();
1244     goto tryAgain;
1245   }
1246
1247   case Stmt::OpaqueValueExprClass:
1248     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1249       E = src;
1250       goto tryAgain;
1251     }
1252     return false;
1253
1254   case Stmt::PredefinedExprClass:
1255     // While __func__, etc., are technically not string literals, they
1256     // cannot contain format specifiers and thus are not a security
1257     // liability.
1258     return true;
1259       
1260   case Stmt::DeclRefExprClass: {
1261     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1262
1263     // As an exception, do not flag errors for variables binding to
1264     // const string literals.
1265     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1266       bool isConstant = false;
1267       QualType T = DR->getType();
1268
1269       if (const ArrayType *AT = Context.getAsArrayType(T)) {
1270         isConstant = AT->getElementType().isConstant(Context);
1271       } else if (const PointerType *PT = T->getAs<PointerType>()) {
1272         isConstant = T.isConstant(Context) &&
1273                      PT->getPointeeType().isConstant(Context);
1274       }
1275
1276       if (isConstant) {
1277         if (const Expr *Init = VD->getAnyInitializer())
1278           return SemaCheckStringLiteral(Init, TheCall,
1279                                         HasVAListArg, format_idx, firstDataArg,
1280                                         isPrintf);
1281       }
1282
1283       // For vprintf* functions (i.e., HasVAListArg==true), we add a
1284       // special check to see if the format string is a function parameter
1285       // of the function calling the printf function.  If the function
1286       // has an attribute indicating it is a printf-like function, then we
1287       // should suppress warnings concerning non-literals being used in a call
1288       // to a vprintf function.  For example:
1289       //
1290       // void
1291       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1292       //      va_list ap;
1293       //      va_start(ap, fmt);
1294       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1295       //      ...
1296       //
1297       //
1298       //  FIXME: We don't have full attribute support yet, so just check to see
1299       //    if the argument is a DeclRefExpr that references a parameter.  We'll
1300       //    add proper support for checking the attribute later.
1301       if (HasVAListArg)
1302         if (isa<ParmVarDecl>(VD))
1303           return true;
1304     }
1305
1306     return false;
1307   }
1308
1309   case Stmt::CallExprClass: {
1310     const CallExpr *CE = cast<CallExpr>(E);
1311     if (const ImplicitCastExpr *ICE
1312           = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1313       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1314         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1315           if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
1316             unsigned ArgIndex = FA->getFormatIdx();
1317             const Expr *Arg = CE->getArg(ArgIndex - 1);
1318
1319             return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
1320                                           format_idx, firstDataArg, isPrintf);
1321           }
1322         }
1323       }
1324     }
1325
1326     return false;
1327   }
1328   case Stmt::ObjCStringLiteralClass:
1329   case Stmt::StringLiteralClass: {
1330     const StringLiteral *StrE = NULL;
1331
1332     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1333       StrE = ObjCFExpr->getString();
1334     else
1335       StrE = cast<StringLiteral>(E);
1336
1337     if (StrE) {
1338       CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1339                         firstDataArg, isPrintf);
1340       return true;
1341     }
1342
1343     return false;
1344   }
1345
1346   default:
1347     return false;
1348   }
1349 }
1350
1351 void
1352 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1353                             const Expr * const *ExprArgs,
1354                             SourceLocation CallSiteLoc) {
1355   for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1356                                   e = NonNull->args_end();
1357        i != e; ++i) {
1358     const Expr *ArgExpr = ExprArgs[*i];
1359     if (ArgExpr->isNullPointerConstant(Context,
1360                                        Expr::NPC_ValueDependentIsNotNull))
1361       Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1362   }
1363 }
1364
1365 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1366 /// functions) for correct use of format strings.
1367 void
1368 Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1369                                 unsigned format_idx, unsigned firstDataArg,
1370                                 bool isPrintf) {
1371
1372   const Expr *Fn = TheCall->getCallee();
1373
1374   // The way the format attribute works in GCC, the implicit this argument
1375   // of member functions is counted. However, it doesn't appear in our own
1376   // lists, so decrement format_idx in that case.
1377   if (isa<CXXMemberCallExpr>(TheCall)) {
1378     const CXXMethodDecl *method_decl =
1379       dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1380     if (method_decl && method_decl->isInstance()) {
1381       // Catch a format attribute mistakenly referring to the object argument.
1382       if (format_idx == 0)
1383         return;
1384       --format_idx;
1385       if(firstDataArg != 0)
1386         --firstDataArg;
1387     }
1388   }
1389
1390   // CHECK: printf/scanf-like function is called with no format string.
1391   if (format_idx >= TheCall->getNumArgs()) {
1392     Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
1393       << Fn->getSourceRange();
1394     return;
1395   }
1396
1397   const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1398
1399   // CHECK: format string is not a string literal.
1400   //
1401   // Dynamically generated format strings are difficult to
1402   // automatically vet at compile time.  Requiring that format strings
1403   // are string literals: (1) permits the checking of format strings by
1404   // the compiler and thereby (2) can practically remove the source of
1405   // many format string exploits.
1406
1407   // Format string can be either ObjC string (e.g. @"%d") or
1408   // C string (e.g. "%d")
1409   // ObjC string uses the same format specifiers as C string, so we can use
1410   // the same format string checking logic for both ObjC and C strings.
1411   if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1412                              firstDataArg, isPrintf))
1413     return;  // Literal format string found, check done!
1414
1415   // If there are no arguments specified, warn with -Wformat-security, otherwise
1416   // warn only with -Wformat-nonliteral.
1417   if (TheCall->getNumArgs() == format_idx+1)
1418     Diag(TheCall->getArg(format_idx)->getLocStart(),
1419          diag::warn_format_nonliteral_noargs)
1420       << OrigFormatExpr->getSourceRange();
1421   else
1422     Diag(TheCall->getArg(format_idx)->getLocStart(),
1423          diag::warn_format_nonliteral)
1424            << OrigFormatExpr->getSourceRange();
1425 }
1426
1427 namespace {
1428 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1429 protected:
1430   Sema &S;
1431   const StringLiteral *FExpr;
1432   const Expr *OrigFormatExpr;
1433   const unsigned FirstDataArg;
1434   const unsigned NumDataArgs;
1435   const bool IsObjCLiteral;
1436   const char *Beg; // Start of format string.
1437   const bool HasVAListArg;
1438   const CallExpr *TheCall;
1439   unsigned FormatIdx;
1440   llvm::BitVector CoveredArgs;
1441   bool usesPositionalArgs;
1442   bool atFirstArg;
1443 public:
1444   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1445                      const Expr *origFormatExpr, unsigned firstDataArg,
1446                      unsigned numDataArgs, bool isObjCLiteral,
1447                      const char *beg, bool hasVAListArg,
1448                      const CallExpr *theCall, unsigned formatIdx)
1449     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1450       FirstDataArg(firstDataArg),
1451       NumDataArgs(numDataArgs),
1452       IsObjCLiteral(isObjCLiteral), Beg(beg),
1453       HasVAListArg(hasVAListArg),
1454       TheCall(theCall), FormatIdx(formatIdx),
1455       usesPositionalArgs(false), atFirstArg(true) {
1456         CoveredArgs.resize(numDataArgs);
1457         CoveredArgs.reset();
1458       }
1459
1460   void DoneProcessing();
1461
1462   void HandleIncompleteSpecifier(const char *startSpecifier,
1463                                  unsigned specifierLen);
1464     
1465   virtual void HandleInvalidPosition(const char *startSpecifier,
1466                                      unsigned specifierLen,
1467                                      analyze_format_string::PositionContext p);
1468
1469   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1470
1471   void HandleNullChar(const char *nullCharacter);
1472
1473 protected:
1474   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1475                                         const char *startSpec,
1476                                         unsigned specifierLen,
1477                                         const char *csStart, unsigned csLen);
1478   
1479   SourceRange getFormatStringRange();
1480   CharSourceRange getSpecifierRange(const char *startSpecifier,
1481                                     unsigned specifierLen);
1482   SourceLocation getLocationOfByte(const char *x);
1483
1484   const Expr *getDataArg(unsigned i) const;
1485   
1486   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1487                     const analyze_format_string::ConversionSpecifier &CS,
1488                     const char *startSpecifier, unsigned specifierLen,
1489                     unsigned argIndex);
1490 };
1491 }
1492
1493 SourceRange CheckFormatHandler::getFormatStringRange() {
1494   return OrigFormatExpr->getSourceRange();
1495 }
1496
1497 CharSourceRange CheckFormatHandler::
1498 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1499   SourceLocation Start = getLocationOfByte(startSpecifier);
1500   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1501
1502   // Advance the end SourceLocation by one due to half-open ranges.
1503   End = End.getLocWithOffset(1);
1504
1505   return CharSourceRange::getCharRange(Start, End);
1506 }
1507
1508 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1509   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1510 }
1511
1512 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1513                                                    unsigned specifierLen){
1514   SourceLocation Loc = getLocationOfByte(startSpecifier);
1515   S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1516     << getSpecifierRange(startSpecifier, specifierLen);
1517 }
1518
1519 void
1520 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1521                                      analyze_format_string::PositionContext p) {
1522   SourceLocation Loc = getLocationOfByte(startPos);
1523   S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1524     << (unsigned) p << getSpecifierRange(startPos, posLen);
1525 }
1526
1527 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1528                                             unsigned posLen) {
1529   SourceLocation Loc = getLocationOfByte(startPos);
1530   S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1531     << getSpecifierRange(startPos, posLen);
1532 }
1533
1534 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1535   if (!IsObjCLiteral) {
1536     // The presence of a null character is likely an error.
1537     S.Diag(getLocationOfByte(nullCharacter),
1538            diag::warn_printf_format_string_contains_null_char)
1539       << getFormatStringRange();
1540   }
1541 }
1542
1543 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1544   return TheCall->getArg(FirstDataArg + i);
1545 }
1546
1547 void CheckFormatHandler::DoneProcessing() {
1548     // Does the number of data arguments exceed the number of
1549     // format conversions in the format string?
1550   if (!HasVAListArg) {
1551       // Find any arguments that weren't covered.
1552     CoveredArgs.flip();
1553     signed notCoveredArg = CoveredArgs.find_first();
1554     if (notCoveredArg >= 0) {
1555       assert((unsigned)notCoveredArg < NumDataArgs);
1556       S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1557              diag::warn_printf_data_arg_not_used)
1558       << getFormatStringRange();
1559     }
1560   }
1561 }
1562
1563 bool
1564 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1565                                                      SourceLocation Loc,
1566                                                      const char *startSpec,
1567                                                      unsigned specifierLen,
1568                                                      const char *csStart,
1569                                                      unsigned csLen) {
1570   
1571   bool keepGoing = true;
1572   if (argIndex < NumDataArgs) {
1573     // Consider the argument coverered, even though the specifier doesn't
1574     // make sense.
1575     CoveredArgs.set(argIndex);
1576   }
1577   else {
1578     // If argIndex exceeds the number of data arguments we
1579     // don't issue a warning because that is just a cascade of warnings (and
1580     // they may have intended '%%' anyway). We don't want to continue processing
1581     // the format string after this point, however, as we will like just get
1582     // gibberish when trying to match arguments.
1583     keepGoing = false;
1584   }
1585   
1586   S.Diag(Loc, diag::warn_format_invalid_conversion)
1587     << StringRef(csStart, csLen)
1588     << getSpecifierRange(startSpec, specifierLen);
1589   
1590   return keepGoing;
1591 }
1592
1593 bool
1594 CheckFormatHandler::CheckNumArgs(
1595   const analyze_format_string::FormatSpecifier &FS,
1596   const analyze_format_string::ConversionSpecifier &CS,
1597   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1598
1599   if (argIndex >= NumDataArgs) {
1600     if (FS.usesPositionalArg())  {
1601       S.Diag(getLocationOfByte(CS.getStart()),
1602              diag::warn_printf_positional_arg_exceeds_data_args)
1603       << (argIndex+1) << NumDataArgs
1604       << getSpecifierRange(startSpecifier, specifierLen);
1605     }
1606     else {
1607       S.Diag(getLocationOfByte(CS.getStart()),
1608              diag::warn_printf_insufficient_data_args)
1609       << getSpecifierRange(startSpecifier, specifierLen);
1610     }
1611     
1612     return false;
1613   }
1614   return true;
1615 }
1616
1617 //===--- CHECK: Printf format string checking ------------------------------===//
1618
1619 namespace {
1620 class CheckPrintfHandler : public CheckFormatHandler {
1621 public:
1622   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1623                      const Expr *origFormatExpr, unsigned firstDataArg,
1624                      unsigned numDataArgs, bool isObjCLiteral,
1625                      const char *beg, bool hasVAListArg,
1626                      const CallExpr *theCall, unsigned formatIdx)
1627   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1628                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1629                        theCall, formatIdx) {}
1630   
1631   
1632   bool HandleInvalidPrintfConversionSpecifier(
1633                                       const analyze_printf::PrintfSpecifier &FS,
1634                                       const char *startSpecifier,
1635                                       unsigned specifierLen);
1636   
1637   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1638                              const char *startSpecifier,
1639                              unsigned specifierLen);
1640   
1641   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1642                     const char *startSpecifier, unsigned specifierLen);
1643   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1644                            const analyze_printf::OptionalAmount &Amt,
1645                            unsigned type,
1646                            const char *startSpecifier, unsigned specifierLen);
1647   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1648                   const analyze_printf::OptionalFlag &flag,
1649                   const char *startSpecifier, unsigned specifierLen);
1650   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1651                          const analyze_printf::OptionalFlag &ignoredFlag,
1652                          const analyze_printf::OptionalFlag &flag,
1653                          const char *startSpecifier, unsigned specifierLen);
1654 };  
1655 }
1656
1657 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1658                                       const analyze_printf::PrintfSpecifier &FS,
1659                                       const char *startSpecifier,
1660                                       unsigned specifierLen) {
1661   const analyze_printf::PrintfConversionSpecifier &CS =
1662     FS.getConversionSpecifier();
1663   
1664   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1665                                           getLocationOfByte(CS.getStart()),
1666                                           startSpecifier, specifierLen,
1667                                           CS.getStart(), CS.getLength());
1668 }
1669
1670 bool CheckPrintfHandler::HandleAmount(
1671                                const analyze_format_string::OptionalAmount &Amt,
1672                                unsigned k, const char *startSpecifier,
1673                                unsigned specifierLen) {
1674
1675   if (Amt.hasDataArgument()) {
1676     if (!HasVAListArg) {
1677       unsigned argIndex = Amt.getArgIndex();
1678       if (argIndex >= NumDataArgs) {
1679         S.Diag(getLocationOfByte(Amt.getStart()),
1680                diag::warn_printf_asterisk_missing_arg)
1681           << k << getSpecifierRange(startSpecifier, specifierLen);
1682         // Don't do any more checking.  We will just emit
1683         // spurious errors.
1684         return false;
1685       }
1686
1687       // Type check the data argument.  It should be an 'int'.
1688       // Although not in conformance with C99, we also allow the argument to be
1689       // an 'unsigned int' as that is a reasonably safe case.  GCC also
1690       // doesn't emit a warning for that case.
1691       CoveredArgs.set(argIndex);
1692       const Expr *Arg = getDataArg(argIndex);
1693       QualType T = Arg->getType();
1694
1695       const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1696       assert(ATR.isValid());
1697
1698       if (!ATR.matchesType(S.Context, T)) {
1699         S.Diag(getLocationOfByte(Amt.getStart()),
1700                diag::warn_printf_asterisk_wrong_type)
1701           << k
1702           << ATR.getRepresentativeType(S.Context) << T
1703           << getSpecifierRange(startSpecifier, specifierLen)
1704           << Arg->getSourceRange();
1705         // Don't do any more checking.  We will just emit
1706         // spurious errors.
1707         return false;
1708       }
1709     }
1710   }
1711   return true;
1712 }
1713
1714 void CheckPrintfHandler::HandleInvalidAmount(
1715                                       const analyze_printf::PrintfSpecifier &FS,
1716                                       const analyze_printf::OptionalAmount &Amt,
1717                                       unsigned type,
1718                                       const char *startSpecifier,
1719                                       unsigned specifierLen) {
1720   const analyze_printf::PrintfConversionSpecifier &CS =
1721     FS.getConversionSpecifier();
1722   switch (Amt.getHowSpecified()) {
1723   case analyze_printf::OptionalAmount::Constant:
1724     S.Diag(getLocationOfByte(Amt.getStart()),
1725         diag::warn_printf_nonsensical_optional_amount)
1726       << type
1727       << CS.toString()
1728       << getSpecifierRange(startSpecifier, specifierLen)
1729       << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1730           Amt.getConstantLength()));
1731     break;
1732
1733   default:
1734     S.Diag(getLocationOfByte(Amt.getStart()),
1735         diag::warn_printf_nonsensical_optional_amount)
1736       << type
1737       << CS.toString()
1738       << getSpecifierRange(startSpecifier, specifierLen);
1739     break;
1740   }
1741 }
1742
1743 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1744                                     const analyze_printf::OptionalFlag &flag,
1745                                     const char *startSpecifier,
1746                                     unsigned specifierLen) {
1747   // Warn about pointless flag with a fixit removal.
1748   const analyze_printf::PrintfConversionSpecifier &CS =
1749     FS.getConversionSpecifier();
1750   S.Diag(getLocationOfByte(flag.getPosition()),
1751       diag::warn_printf_nonsensical_flag)
1752     << flag.toString() << CS.toString()
1753     << getSpecifierRange(startSpecifier, specifierLen)
1754     << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
1755 }
1756
1757 void CheckPrintfHandler::HandleIgnoredFlag(
1758                                 const analyze_printf::PrintfSpecifier &FS,
1759                                 const analyze_printf::OptionalFlag &ignoredFlag,
1760                                 const analyze_printf::OptionalFlag &flag,
1761                                 const char *startSpecifier,
1762                                 unsigned specifierLen) {
1763   // Warn about ignored flag with a fixit removal.
1764   S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1765       diag::warn_printf_ignored_flag)
1766     << ignoredFlag.toString() << flag.toString()
1767     << getSpecifierRange(startSpecifier, specifierLen)
1768     << FixItHint::CreateRemoval(getSpecifierRange(
1769         ignoredFlag.getPosition(), 1));
1770 }
1771
1772 bool
1773 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1774                                             &FS,
1775                                           const char *startSpecifier,
1776                                           unsigned specifierLen) {
1777
1778   using namespace analyze_format_string;
1779   using namespace analyze_printf;  
1780   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
1781
1782   if (FS.consumesDataArgument()) {
1783     if (atFirstArg) {
1784         atFirstArg = false;
1785         usesPositionalArgs = FS.usesPositionalArg();
1786     }
1787     else if (usesPositionalArgs != FS.usesPositionalArg()) {
1788       // Cannot mix-and-match positional and non-positional arguments.
1789       S.Diag(getLocationOfByte(CS.getStart()),
1790              diag::warn_format_mix_positional_nonpositional_args)
1791         << getSpecifierRange(startSpecifier, specifierLen);
1792       return false;
1793     }
1794   }
1795
1796   // First check if the field width, precision, and conversion specifier
1797   // have matching data arguments.
1798   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1799                     startSpecifier, specifierLen)) {
1800     return false;
1801   }
1802
1803   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1804                     startSpecifier, specifierLen)) {
1805     return false;
1806   }
1807
1808   if (!CS.consumesDataArgument()) {
1809     // FIXME: Technically specifying a precision or field width here
1810     // makes no sense.  Worth issuing a warning at some point.
1811     return true;
1812   }
1813
1814   // Consume the argument.
1815   unsigned argIndex = FS.getArgIndex();
1816   if (argIndex < NumDataArgs) {
1817     // The check to see if the argIndex is valid will come later.
1818     // We set the bit here because we may exit early from this
1819     // function if we encounter some other error.
1820     CoveredArgs.set(argIndex);
1821   }
1822
1823   // FreeBSD extensions
1824   if (CS.getKind() == ConversionSpecifier::bArg || CS.getKind() == ConversionSpecifier::DArg) { 
1825      // claim the second argument
1826      CoveredArgs.set(argIndex + 1);
1827
1828     // Now type check the data expression that matches the
1829     // format specifier.
1830     const Expr *Ex = getDataArg(argIndex);
1831     const analyze_printf::ArgTypeResult &ATR = 
1832       (CS.getKind() == ConversionSpecifier::bArg) ?
1833         ArgTypeResult(S.Context.IntTy) : ArgTypeResult::CStrTy;
1834     if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType()))
1835       S.Diag(getLocationOfByte(CS.getStart()),
1836              diag::warn_printf_conversion_argument_type_mismatch)
1837         << ATR.getRepresentativeType(S.Context) << Ex->getType()
1838         << getSpecifierRange(startSpecifier, specifierLen)
1839         << Ex->getSourceRange();
1840
1841     // Now type check the data expression that matches the
1842     // format specifier.
1843     Ex = getDataArg(argIndex + 1);
1844     const analyze_printf::ArgTypeResult &ATR2 = ArgTypeResult::CStrTy;
1845     if (ATR2.isValid() && !ATR2.matchesType(S.Context, Ex->getType()))
1846       S.Diag(getLocationOfByte(CS.getStart()),
1847              diag::warn_printf_conversion_argument_type_mismatch)
1848         << ATR2.getRepresentativeType(S.Context) << Ex->getType()
1849         << getSpecifierRange(startSpecifier, specifierLen)
1850         << Ex->getSourceRange();
1851
1852      return true;
1853   }
1854   // END OF FREEBSD EXTENSIONS
1855
1856   // Check for using an Objective-C specific conversion specifier
1857   // in a non-ObjC literal.
1858   if (!IsObjCLiteral && CS.isObjCArg()) {
1859     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1860                                                   specifierLen);
1861   }
1862
1863   // Check for invalid use of field width
1864   if (!FS.hasValidFieldWidth()) {
1865     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
1866         startSpecifier, specifierLen);
1867   }
1868
1869   // Check for invalid use of precision
1870   if (!FS.hasValidPrecision()) {
1871     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1872         startSpecifier, specifierLen);
1873   }
1874
1875   // Check each flag does not conflict with any other component.
1876   if (!FS.hasValidThousandsGroupingPrefix())
1877     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
1878   if (!FS.hasValidLeadingZeros())
1879     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1880   if (!FS.hasValidPlusPrefix())
1881     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
1882   if (!FS.hasValidSpacePrefix())
1883     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
1884   if (!FS.hasValidAlternativeForm())
1885     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1886   if (!FS.hasValidLeftJustified())
1887     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1888
1889   // Check that flags are not ignored by another flag
1890   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1891     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1892         startSpecifier, specifierLen);
1893   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1894     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1895             startSpecifier, specifierLen);
1896
1897   // Check the length modifier is valid with the given conversion specifier.
1898   const LengthModifier &LM = FS.getLengthModifier();
1899   if (!FS.hasValidLengthModifier())
1900     S.Diag(getLocationOfByte(LM.getStart()),
1901         diag::warn_format_nonsensical_length)
1902       << LM.toString() << CS.toString()
1903       << getSpecifierRange(startSpecifier, specifierLen)
1904       << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1905           LM.getLength()));
1906
1907   // Are we using '%n'?
1908   if (CS.getKind() == ConversionSpecifier::nArg) {
1909     // Issue a warning about this being a possible security issue.
1910     S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1911       << getSpecifierRange(startSpecifier, specifierLen);
1912     // Continue checking the other format specifiers.
1913     return true;
1914   }
1915
1916   // The remaining checks depend on the data arguments.
1917   if (HasVAListArg)
1918     return true;
1919
1920   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
1921     return false;
1922
1923   // Now type check the data expression that matches the
1924   // format specifier.
1925   const Expr *Ex = getDataArg(argIndex);
1926   const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1927   if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1928     // Check if we didn't match because of an implicit cast from a 'char'
1929     // or 'short' to an 'int'.  This is done because printf is a varargs
1930     // function.
1931     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1932       if (ICE->getType() == S.Context.IntTy) {
1933         // All further checking is done on the subexpression.
1934         Ex = ICE->getSubExpr();
1935         if (ATR.matchesType(S.Context, Ex->getType()))
1936           return true;
1937       }
1938
1939     // We may be able to offer a FixItHint if it is a supported type.
1940     PrintfSpecifier fixedFS = FS;
1941     bool success = fixedFS.fixType(Ex->getType());
1942
1943     if (success) {
1944       // Get the fix string from the fixed format specifier
1945       llvm::SmallString<128> buf;
1946       llvm::raw_svector_ostream os(buf);
1947       fixedFS.toString(os);
1948
1949       // FIXME: getRepresentativeType() perhaps should return a string
1950       // instead of a QualType to better handle when the representative
1951       // type is 'wint_t' (which is defined in the system headers).
1952       S.Diag(getLocationOfByte(CS.getStart()),
1953           diag::warn_printf_conversion_argument_type_mismatch)
1954         << ATR.getRepresentativeType(S.Context) << Ex->getType()
1955         << getSpecifierRange(startSpecifier, specifierLen)
1956         << Ex->getSourceRange()
1957         << FixItHint::CreateReplacement(
1958             getSpecifierRange(startSpecifier, specifierLen),
1959             os.str());
1960     }
1961     else {
1962       S.Diag(getLocationOfByte(CS.getStart()),
1963              diag::warn_printf_conversion_argument_type_mismatch)
1964         << ATR.getRepresentativeType(S.Context) << Ex->getType()
1965         << getSpecifierRange(startSpecifier, specifierLen)
1966         << Ex->getSourceRange();
1967     }
1968   }
1969
1970   return true;
1971 }
1972
1973 //===--- CHECK: Scanf format string checking ------------------------------===//
1974
1975 namespace {  
1976 class CheckScanfHandler : public CheckFormatHandler {
1977 public:
1978   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1979                     const Expr *origFormatExpr, unsigned firstDataArg,
1980                     unsigned numDataArgs, bool isObjCLiteral,
1981                     const char *beg, bool hasVAListArg,
1982                     const CallExpr *theCall, unsigned formatIdx)
1983   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1984                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1985                        theCall, formatIdx) {}
1986   
1987   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1988                             const char *startSpecifier,
1989                             unsigned specifierLen);
1990   
1991   bool HandleInvalidScanfConversionSpecifier(
1992           const analyze_scanf::ScanfSpecifier &FS,
1993           const char *startSpecifier,
1994           unsigned specifierLen);
1995
1996   void HandleIncompleteScanList(const char *start, const char *end);
1997 };
1998 }
1999
2000 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2001                                                  const char *end) {
2002   S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
2003     << getSpecifierRange(start, end - start);
2004 }
2005
2006 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2007                                         const analyze_scanf::ScanfSpecifier &FS,
2008                                         const char *startSpecifier,
2009                                         unsigned specifierLen) {
2010
2011   const analyze_scanf::ScanfConversionSpecifier &CS =
2012     FS.getConversionSpecifier();
2013
2014   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2015                                           getLocationOfByte(CS.getStart()),
2016                                           startSpecifier, specifierLen,
2017                                           CS.getStart(), CS.getLength());
2018 }
2019
2020 bool CheckScanfHandler::HandleScanfSpecifier(
2021                                        const analyze_scanf::ScanfSpecifier &FS,
2022                                        const char *startSpecifier,
2023                                        unsigned specifierLen) {
2024   
2025   using namespace analyze_scanf;
2026   using namespace analyze_format_string;  
2027
2028   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
2029
2030   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
2031   // be used to decide if we are using positional arguments consistently.
2032   if (FS.consumesDataArgument()) {
2033     if (atFirstArg) {
2034       atFirstArg = false;
2035       usesPositionalArgs = FS.usesPositionalArg();
2036     }
2037     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2038       // Cannot mix-and-match positional and non-positional arguments.
2039       S.Diag(getLocationOfByte(CS.getStart()),
2040              diag::warn_format_mix_positional_nonpositional_args)
2041         << getSpecifierRange(startSpecifier, specifierLen);
2042       return false;
2043     }
2044   }
2045   
2046   // Check if the field with is non-zero.
2047   const OptionalAmount &Amt = FS.getFieldWidth();
2048   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2049     if (Amt.getConstantAmount() == 0) {
2050       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2051                                                    Amt.getConstantLength());
2052       S.Diag(getLocationOfByte(Amt.getStart()),
2053              diag::warn_scanf_nonzero_width)
2054         << R << FixItHint::CreateRemoval(R);
2055     }
2056   }
2057   
2058   if (!FS.consumesDataArgument()) {
2059     // FIXME: Technically specifying a precision or field width here
2060     // makes no sense.  Worth issuing a warning at some point.
2061     return true;
2062   }
2063   
2064   // Consume the argument.
2065   unsigned argIndex = FS.getArgIndex();
2066   if (argIndex < NumDataArgs) {
2067       // The check to see if the argIndex is valid will come later.
2068       // We set the bit here because we may exit early from this
2069       // function if we encounter some other error.
2070     CoveredArgs.set(argIndex);
2071   }
2072   
2073   // Check the length modifier is valid with the given conversion specifier.
2074   const LengthModifier &LM = FS.getLengthModifier();
2075   if (!FS.hasValidLengthModifier()) {
2076     S.Diag(getLocationOfByte(LM.getStart()),
2077            diag::warn_format_nonsensical_length)
2078       << LM.toString() << CS.toString()
2079       << getSpecifierRange(startSpecifier, specifierLen)
2080       << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2081                                                     LM.getLength()));
2082   }
2083
2084   // The remaining checks depend on the data arguments.
2085   if (HasVAListArg)
2086     return true;
2087   
2088   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2089     return false;
2090   
2091   // FIXME: Check that the argument type matches the format specifier.
2092   
2093   return true;
2094 }
2095
2096 void Sema::CheckFormatString(const StringLiteral *FExpr,
2097                              const Expr *OrigFormatExpr,
2098                              const CallExpr *TheCall, bool HasVAListArg,
2099                              unsigned format_idx, unsigned firstDataArg,
2100                              bool isPrintf) {
2101   
2102   // CHECK: is the format string a wide literal?
2103   if (!FExpr->isAscii()) {
2104     Diag(FExpr->getLocStart(),
2105          diag::warn_format_string_is_wide_literal)
2106     << OrigFormatExpr->getSourceRange();
2107     return;
2108   }
2109   
2110   // Str - The format string.  NOTE: this is NOT null-terminated!
2111   StringRef StrRef = FExpr->getString();
2112   const char *Str = StrRef.data();
2113   unsigned StrLen = StrRef.size();
2114   const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
2115   
2116   // CHECK: empty format string?
2117   if (StrLen == 0 && numDataArgs > 0) {
2118     Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
2119     << OrigFormatExpr->getSourceRange();
2120     return;
2121   }
2122   
2123   if (isPrintf) {
2124     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2125                          numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2126                          Str, HasVAListArg, TheCall, format_idx);
2127   
2128     bool FormatExtensions = getLangOptions().FormatExtensions;
2129     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2130                                                   FormatExtensions))
2131       H.DoneProcessing();
2132   }
2133   else {
2134     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2135                         numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2136                         Str, HasVAListArg, TheCall, format_idx);
2137     
2138     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2139       H.DoneProcessing();
2140   }
2141 }
2142
2143 //===--- CHECK: Standard memory functions ---------------------------------===//
2144
2145 /// \brief Determine whether the given type is a dynamic class type (e.g.,
2146 /// whether it has a vtable).
2147 static bool isDynamicClassType(QualType T) {
2148   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2149     if (CXXRecordDecl *Definition = Record->getDefinition())
2150       if (Definition->isDynamicClass())
2151         return true;
2152   
2153   return false;
2154 }
2155
2156 /// \brief If E is a sizeof expression, returns its argument expression,
2157 /// otherwise returns NULL.
2158 static const Expr *getSizeOfExprArg(const Expr* E) {
2159   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2160       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2161     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2162       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
2163
2164   return 0;
2165 }
2166
2167 /// \brief If E is a sizeof expression, returns its argument type.
2168 static QualType getSizeOfArgType(const Expr* E) {
2169   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2170       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2171     if (SizeOf->getKind() == clang::UETT_SizeOf)
2172       return SizeOf->getTypeOfArgument();
2173
2174   return QualType();
2175 }
2176
2177 /// \brief Check for dangerous or invalid arguments to memset().
2178 ///
2179 /// This issues warnings on known problematic, dangerous or unspecified
2180 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2181 /// function calls.
2182 ///
2183 /// \param Call The call expression to diagnose.
2184 void Sema::CheckMemaccessArguments(const CallExpr *Call,
2185                                    CheckedMemoryFunction CMF,
2186                                    IdentifierInfo *FnName) {
2187   // It is possible to have a non-standard definition of memset.  Validate
2188   // we have enough arguments, and if not, abort further checking.
2189   unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2190   if (Call->getNumArgs() < ExpectedNumArgs)
2191     return;
2192
2193   unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2194   unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2195   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
2196
2197   // We have special checking when the length is a sizeof expression.
2198   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2199   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2200   llvm::FoldingSetNodeID SizeOfArgID;
2201
2202   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2203     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
2204     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
2205
2206     QualType DestTy = Dest->getType();
2207     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2208       QualType PointeeTy = DestPtrTy->getPointeeType();
2209
2210       // Never warn about void type pointers. This can be used to suppress
2211       // false positives.
2212       if (PointeeTy->isVoidType())
2213         continue;
2214
2215       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2216       // actually comparing the expressions for equality. Because computing the
2217       // expression IDs can be expensive, we only do this if the diagnostic is
2218       // enabled.
2219       if (SizeOfArg &&
2220           Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2221                                    SizeOfArg->getExprLoc())) {
2222         // We only compute IDs for expressions if the warning is enabled, and
2223         // cache the sizeof arg's ID.
2224         if (SizeOfArgID == llvm::FoldingSetNodeID())
2225           SizeOfArg->Profile(SizeOfArgID, Context, true);
2226         llvm::FoldingSetNodeID DestID;
2227         Dest->Profile(DestID, Context, true);
2228         if (DestID == SizeOfArgID) {
2229           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2230           //       over sizeof(src) as well.
2231           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2232           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2233             if (UnaryOp->getOpcode() == UO_AddrOf)
2234               ActionIdx = 1; // If its an address-of operator, just remove it.
2235           if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2236             ActionIdx = 2; // If the pointee's size is sizeof(char),
2237                            // suggest an explicit length.
2238           unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
2239           DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2240                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
2241                                 << FnName << DestSrcSelect << ActionIdx
2242                                 << Dest->getSourceRange()
2243                                 << SizeOfArg->getSourceRange());
2244           break;
2245         }
2246       }
2247
2248       // Also check for cases where the sizeof argument is the exact same
2249       // type as the memory argument, and where it points to a user-defined
2250       // record type.
2251       if (SizeOfArgTy != QualType()) {
2252         if (PointeeTy->isRecordType() &&
2253             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2254           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2255                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
2256                                 << FnName << SizeOfArgTy << ArgIdx
2257                                 << PointeeTy << Dest->getSourceRange()
2258                                 << LenExpr->getSourceRange());
2259           break;
2260         }
2261       }
2262
2263       // Always complain about dynamic classes.
2264       if (isDynamicClassType(PointeeTy))
2265         DiagRuntimeBehavior(
2266           Dest->getExprLoc(), Dest,
2267           PDiag(diag::warn_dyn_class_memaccess)
2268             << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2269             // "overwritten" if we're warning about the destination for any call
2270             // but memcmp; otherwise a verb appropriate to the call.
2271             << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2272             << Call->getCallee()->getSourceRange());
2273       else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
2274         DiagRuntimeBehavior(
2275           Dest->getExprLoc(), Dest,
2276           PDiag(diag::warn_arc_object_memaccess)
2277             << ArgIdx << FnName << PointeeTy
2278             << Call->getCallee()->getSourceRange());
2279       else
2280         continue;
2281
2282       DiagRuntimeBehavior(
2283         Dest->getExprLoc(), Dest,
2284         PDiag(diag::note_bad_memaccess_silence)
2285           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2286       break;
2287     }
2288   }
2289 }
2290
2291 // A little helper routine: ignore addition and subtraction of integer literals.
2292 // This intentionally does not ignore all integer constant expressions because
2293 // we don't want to remove sizeof().
2294 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2295   Ex = Ex->IgnoreParenCasts();
2296
2297   for (;;) {
2298     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2299     if (!BO || !BO->isAdditiveOp())
2300       break;
2301
2302     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2303     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2304     
2305     if (isa<IntegerLiteral>(RHS))
2306       Ex = LHS;
2307     else if (isa<IntegerLiteral>(LHS))
2308       Ex = RHS;
2309     else
2310       break;
2311   }
2312
2313   return Ex;
2314 }
2315
2316 // Warn if the user has made the 'size' argument to strlcpy or strlcat
2317 // be the size of the source, instead of the destination.
2318 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2319                                     IdentifierInfo *FnName) {
2320
2321   // Don't crash if the user has the wrong number of arguments
2322   if (Call->getNumArgs() != 3)
2323     return;
2324
2325   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2326   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2327   const Expr *CompareWithSrc = NULL;
2328   
2329   // Look for 'strlcpy(dst, x, sizeof(x))'
2330   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2331     CompareWithSrc = Ex;
2332   else {
2333     // Look for 'strlcpy(dst, x, strlen(x))'
2334     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2335       if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2336           && SizeCall->getNumArgs() == 1)
2337         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2338     }
2339   }
2340
2341   if (!CompareWithSrc)
2342     return;
2343
2344   // Determine if the argument to sizeof/strlen is equal to the source
2345   // argument.  In principle there's all kinds of things you could do
2346   // here, for instance creating an == expression and evaluating it with
2347   // EvaluateAsBooleanCondition, but this uses a more direct technique:
2348   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2349   if (!SrcArgDRE)
2350     return;
2351   
2352   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2353   if (!CompareWithSrcDRE || 
2354       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2355     return;
2356   
2357   const Expr *OriginalSizeArg = Call->getArg(2);
2358   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2359     << OriginalSizeArg->getSourceRange() << FnName;
2360   
2361   // Output a FIXIT hint if the destination is an array (rather than a
2362   // pointer to an array).  This could be enhanced to handle some
2363   // pointers if we know the actual size, like if DstArg is 'array+2'
2364   // we could say 'sizeof(array)-2'.
2365   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
2366   QualType DstArgTy = DstArg->getType();
2367   
2368   // Only handle constant-sized or VLAs, but not flexible members.
2369   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2370     // Only issue the FIXIT for arrays of size > 1.
2371     if (CAT->getSize().getSExtValue() <= 1)
2372       return;
2373   } else if (!DstArgTy->isVariableArrayType()) {
2374     return;
2375   }
2376
2377   llvm::SmallString<128> sizeString;
2378   llvm::raw_svector_ostream OS(sizeString);
2379   OS << "sizeof(";
2380   DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2381   OS << ")";
2382   
2383   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2384     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2385                                     OS.str());
2386 }
2387
2388 //===--- CHECK: Return Address of Stack Variable --------------------------===//
2389
2390 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2391 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
2392
2393 /// CheckReturnStackAddr - Check if a return statement returns the address
2394 ///   of a stack variable.
2395 void
2396 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2397                            SourceLocation ReturnLoc) {
2398
2399   Expr *stackE = 0;
2400   SmallVector<DeclRefExpr *, 8> refVars;
2401
2402   // Perform checking for returned stack addresses, local blocks,
2403   // label addresses or references to temporaries.
2404   if (lhsType->isPointerType() ||
2405       (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
2406     stackE = EvalAddr(RetValExp, refVars);
2407   } else if (lhsType->isReferenceType()) {
2408     stackE = EvalVal(RetValExp, refVars);
2409   }
2410
2411   if (stackE == 0)
2412     return; // Nothing suspicious was found.
2413
2414   SourceLocation diagLoc;
2415   SourceRange diagRange;
2416   if (refVars.empty()) {
2417     diagLoc = stackE->getLocStart();
2418     diagRange = stackE->getSourceRange();
2419   } else {
2420     // We followed through a reference variable. 'stackE' contains the
2421     // problematic expression but we will warn at the return statement pointing
2422     // at the reference variable. We will later display the "trail" of
2423     // reference variables using notes.
2424     diagLoc = refVars[0]->getLocStart();
2425     diagRange = refVars[0]->getSourceRange();
2426   }
2427
2428   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2429     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2430                                              : diag::warn_ret_stack_addr)
2431      << DR->getDecl()->getDeclName() << diagRange;
2432   } else if (isa<BlockExpr>(stackE)) { // local block.
2433     Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2434   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2435     Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2436   } else { // local temporary.
2437     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2438                                              : diag::warn_ret_local_temp_addr)
2439      << diagRange;
2440   }
2441
2442   // Display the "trail" of reference variables that we followed until we
2443   // found the problematic expression using notes.
2444   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2445     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2446     // If this var binds to another reference var, show the range of the next
2447     // var, otherwise the var binds to the problematic expression, in which case
2448     // show the range of the expression.
2449     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2450                                   : stackE->getSourceRange();
2451     Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2452       << VD->getDeclName() << range;
2453   }
2454 }
2455
2456 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2457 ///  check if the expression in a return statement evaluates to an address
2458 ///  to a location on the stack, a local block, an address of a label, or a
2459 ///  reference to local temporary. The recursion is used to traverse the
2460 ///  AST of the return expression, with recursion backtracking when we
2461 ///  encounter a subexpression that (1) clearly does not lead to one of the
2462 ///  above problematic expressions (2) is something we cannot determine leads to
2463 ///  a problematic expression based on such local checking.
2464 ///
2465 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
2466 ///  the expression that they point to. Such variables are added to the
2467 ///  'refVars' vector so that we know what the reference variable "trail" was.
2468 ///
2469 ///  EvalAddr processes expressions that are pointers that are used as
2470 ///  references (and not L-values).  EvalVal handles all other values.
2471 ///  At the base case of the recursion is a check for the above problematic
2472 ///  expressions.
2473 ///
2474 ///  This implementation handles:
2475 ///
2476 ///   * pointer-to-pointer casts
2477 ///   * implicit conversions from array references to pointers
2478 ///   * taking the address of fields
2479 ///   * arbitrary interplay between "&" and "*" operators
2480 ///   * pointer arithmetic from an address of a stack variable
2481 ///   * taking the address of an array element where the array is on the stack
2482 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2483   if (E->isTypeDependent())
2484       return NULL;
2485
2486   // We should only be called for evaluating pointer expressions.
2487   assert((E->getType()->isAnyPointerType() ||
2488           E->getType()->isBlockPointerType() ||
2489           E->getType()->isObjCQualifiedIdType()) &&
2490          "EvalAddr only works on pointers");
2491
2492   E = E->IgnoreParens();
2493
2494   // Our "symbolic interpreter" is just a dispatch off the currently
2495   // viewed AST node.  We then recursively traverse the AST by calling
2496   // EvalAddr and EvalVal appropriately.
2497   switch (E->getStmtClass()) {
2498   case Stmt::DeclRefExprClass: {
2499     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2500
2501     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2502       // If this is a reference variable, follow through to the expression that
2503       // it points to.
2504       if (V->hasLocalStorage() &&
2505           V->getType()->isReferenceType() && V->hasInit()) {
2506         // Add the reference variable to the "trail".
2507         refVars.push_back(DR);
2508         return EvalAddr(V->getInit(), refVars);
2509       }
2510
2511     return NULL;
2512   }
2513
2514   case Stmt::UnaryOperatorClass: {
2515     // The only unary operator that make sense to handle here
2516     // is AddrOf.  All others don't make sense as pointers.
2517     UnaryOperator *U = cast<UnaryOperator>(E);
2518
2519     if (U->getOpcode() == UO_AddrOf)
2520       return EvalVal(U->getSubExpr(), refVars);
2521     else
2522       return NULL;
2523   }
2524
2525   case Stmt::BinaryOperatorClass: {
2526     // Handle pointer arithmetic.  All other binary operators are not valid
2527     // in this context.
2528     BinaryOperator *B = cast<BinaryOperator>(E);
2529     BinaryOperatorKind op = B->getOpcode();
2530
2531     if (op != BO_Add && op != BO_Sub)
2532       return NULL;
2533
2534     Expr *Base = B->getLHS();
2535
2536     // Determine which argument is the real pointer base.  It could be
2537     // the RHS argument instead of the LHS.
2538     if (!Base->getType()->isPointerType()) Base = B->getRHS();
2539
2540     assert (Base->getType()->isPointerType());
2541     return EvalAddr(Base, refVars);
2542   }
2543
2544   // For conditional operators we need to see if either the LHS or RHS are
2545   // valid DeclRefExpr*s.  If one of them is valid, we return it.
2546   case Stmt::ConditionalOperatorClass: {
2547     ConditionalOperator *C = cast<ConditionalOperator>(E);
2548
2549     // Handle the GNU extension for missing LHS.
2550     if (Expr *lhsExpr = C->getLHS()) {
2551     // In C++, we can have a throw-expression, which has 'void' type.
2552       if (!lhsExpr->getType()->isVoidType())
2553         if (Expr* LHS = EvalAddr(lhsExpr, refVars))
2554           return LHS;
2555     }
2556
2557     // In C++, we can have a throw-expression, which has 'void' type.
2558     if (C->getRHS()->getType()->isVoidType())
2559       return NULL;
2560
2561     return EvalAddr(C->getRHS(), refVars);
2562   }
2563   
2564   case Stmt::BlockExprClass:
2565     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
2566       return E; // local block.
2567     return NULL;
2568
2569   case Stmt::AddrLabelExprClass:
2570     return E; // address of label.
2571
2572   // For casts, we need to handle conversions from arrays to
2573   // pointer values, and pointer-to-pointer conversions.
2574   case Stmt::ImplicitCastExprClass:
2575   case Stmt::CStyleCastExprClass:
2576   case Stmt::CXXFunctionalCastExprClass:
2577   case Stmt::ObjCBridgedCastExprClass: {
2578     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2579     QualType T = SubExpr->getType();
2580
2581     if (SubExpr->getType()->isPointerType() ||
2582         SubExpr->getType()->isBlockPointerType() ||
2583         SubExpr->getType()->isObjCQualifiedIdType())
2584       return EvalAddr(SubExpr, refVars);
2585     else if (T->isArrayType())
2586       return EvalVal(SubExpr, refVars);
2587     else
2588       return 0;
2589   }
2590
2591   // C++ casts.  For dynamic casts, static casts, and const casts, we
2592   // are always converting from a pointer-to-pointer, so we just blow
2593   // through the cast.  In the case the dynamic cast doesn't fail (and
2594   // return NULL), we take the conservative route and report cases
2595   // where we return the address of a stack variable.  For Reinterpre
2596   // FIXME: The comment about is wrong; we're not always converting
2597   // from pointer to pointer. I'm guessing that this code should also
2598   // handle references to objects.
2599   case Stmt::CXXStaticCastExprClass:
2600   case Stmt::CXXDynamicCastExprClass:
2601   case Stmt::CXXConstCastExprClass:
2602   case Stmt::CXXReinterpretCastExprClass: {
2603       Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
2604       if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
2605         return EvalAddr(S, refVars);
2606       else
2607         return NULL;
2608   }
2609
2610   case Stmt::MaterializeTemporaryExprClass:
2611     if (Expr *Result = EvalAddr(
2612                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2613                                 refVars))
2614       return Result;
2615       
2616     return E;
2617       
2618   // Everything else: we simply don't reason about them.
2619   default:
2620     return NULL;
2621   }
2622 }
2623
2624
2625 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
2626 ///   See the comments for EvalAddr for more details.
2627 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2628 do {
2629   // We should only be called for evaluating non-pointer expressions, or
2630   // expressions with a pointer type that are not used as references but instead
2631   // are l-values (e.g., DeclRefExpr with a pointer type).
2632
2633   // Our "symbolic interpreter" is just a dispatch off the currently
2634   // viewed AST node.  We then recursively traverse the AST by calling
2635   // EvalAddr and EvalVal appropriately.
2636
2637   E = E->IgnoreParens();
2638   switch (E->getStmtClass()) {
2639   case Stmt::ImplicitCastExprClass: {
2640     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
2641     if (IE->getValueKind() == VK_LValue) {
2642       E = IE->getSubExpr();
2643       continue;
2644     }
2645     return NULL;
2646   }
2647
2648   case Stmt::DeclRefExprClass: {
2649     // When we hit a DeclRefExpr we are looking at code that refers to a
2650     // variable's name. If it's not a reference variable we check if it has
2651     // local storage within the function, and if so, return the expression.
2652     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2653
2654     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2655       if (V->hasLocalStorage()) {
2656         if (!V->getType()->isReferenceType())
2657           return DR;
2658
2659         // Reference variable, follow through to the expression that
2660         // it points to.
2661         if (V->hasInit()) {
2662           // Add the reference variable to the "trail".
2663           refVars.push_back(DR);
2664           return EvalVal(V->getInit(), refVars);
2665         }
2666       }
2667
2668     return NULL;
2669   }
2670
2671   case Stmt::UnaryOperatorClass: {
2672     // The only unary operator that make sense to handle here
2673     // is Deref.  All others don't resolve to a "name."  This includes
2674     // handling all sorts of rvalues passed to a unary operator.
2675     UnaryOperator *U = cast<UnaryOperator>(E);
2676
2677     if (U->getOpcode() == UO_Deref)
2678       return EvalAddr(U->getSubExpr(), refVars);
2679
2680     return NULL;
2681   }
2682
2683   case Stmt::ArraySubscriptExprClass: {
2684     // Array subscripts are potential references to data on the stack.  We
2685     // retrieve the DeclRefExpr* for the array variable if it indeed
2686     // has local storage.
2687     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
2688   }
2689
2690   case Stmt::ConditionalOperatorClass: {
2691     // For conditional operators we need to see if either the LHS or RHS are
2692     // non-NULL Expr's.  If one is non-NULL, we return it.
2693     ConditionalOperator *C = cast<ConditionalOperator>(E);
2694
2695     // Handle the GNU extension for missing LHS.
2696     if (Expr *lhsExpr = C->getLHS())
2697       if (Expr *LHS = EvalVal(lhsExpr, refVars))
2698         return LHS;
2699
2700     return EvalVal(C->getRHS(), refVars);
2701   }
2702
2703   // Accesses to members are potential references to data on the stack.
2704   case Stmt::MemberExprClass: {
2705     MemberExpr *M = cast<MemberExpr>(E);
2706
2707     // Check for indirect access.  We only want direct field accesses.
2708     if (M->isArrow())
2709       return NULL;
2710
2711     // Check whether the member type is itself a reference, in which case
2712     // we're not going to refer to the member, but to what the member refers to.
2713     if (M->getMemberDecl()->getType()->isReferenceType())
2714       return NULL;
2715
2716     return EvalVal(M->getBase(), refVars);
2717   }
2718
2719   case Stmt::MaterializeTemporaryExprClass:
2720     if (Expr *Result = EvalVal(
2721                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2722                                refVars))
2723       return Result;
2724       
2725     return E;
2726
2727   default:
2728     // Check that we don't return or take the address of a reference to a
2729     // temporary. This is only useful in C++.
2730     if (!E->isTypeDependent() && E->isRValue())
2731       return E;
2732
2733     // Everything else: we simply don't reason about them.
2734     return NULL;
2735   }
2736 } while (true);
2737 }
2738
2739 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2740
2741 /// Check for comparisons of floating point operands using != and ==.
2742 /// Issue a warning if these are no self-comparisons, as they are not likely
2743 /// to do what the programmer intended.
2744 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
2745   bool EmitWarning = true;
2746
2747   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2748   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
2749
2750   // Special case: check for x == x (which is OK).
2751   // Do not emit warnings for such cases.
2752   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2753     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2754       if (DRL->getDecl() == DRR->getDecl())
2755         EmitWarning = false;
2756
2757
2758   // Special case: check for comparisons against literals that can be exactly
2759   //  represented by APFloat.  In such cases, do not emit a warning.  This
2760   //  is a heuristic: often comparison against such literals are used to
2761   //  detect if a value in a variable has not changed.  This clearly can
2762   //  lead to false negatives.
2763   if (EmitWarning) {
2764     if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2765       if (FLL->isExact())
2766         EmitWarning = false;
2767     } else
2768       if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2769         if (FLR->isExact())
2770           EmitWarning = false;
2771     }
2772   }
2773
2774   // Check for comparisons with builtin types.
2775   if (EmitWarning)
2776     if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
2777       if (CL->isBuiltinCall(Context))
2778         EmitWarning = false;
2779
2780   if (EmitWarning)
2781     if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
2782       if (CR->isBuiltinCall(Context))
2783         EmitWarning = false;
2784
2785   // Emit the diagnostic.
2786   if (EmitWarning)
2787     Diag(Loc, diag::warn_floatingpoint_eq)
2788       << LHS->getSourceRange() << RHS->getSourceRange();
2789 }
2790
2791 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2792 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2793
2794 namespace {
2795
2796 /// Structure recording the 'active' range of an integer-valued
2797 /// expression.
2798 struct IntRange {
2799   /// The number of bits active in the int.
2800   unsigned Width;
2801
2802   /// True if the int is known not to have negative values.
2803   bool NonNegative;
2804
2805   IntRange(unsigned Width, bool NonNegative)
2806     : Width(Width), NonNegative(NonNegative)
2807   {}
2808
2809   /// Returns the range of the bool type.
2810   static IntRange forBoolType() {
2811     return IntRange(1, true);
2812   }
2813
2814   /// Returns the range of an opaque value of the given integral type.
2815   static IntRange forValueOfType(ASTContext &C, QualType T) {
2816     return forValueOfCanonicalType(C,
2817                           T->getCanonicalTypeInternal().getTypePtr());
2818   }
2819
2820   /// Returns the range of an opaque value of a canonical integral type.
2821   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
2822     assert(T->isCanonicalUnqualified());
2823
2824     if (const VectorType *VT = dyn_cast<VectorType>(T))
2825       T = VT->getElementType().getTypePtr();
2826     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2827       T = CT->getElementType().getTypePtr();
2828
2829     // For enum types, use the known bit width of the enumerators.
2830     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2831       EnumDecl *Enum = ET->getDecl();
2832       if (!Enum->isCompleteDefinition())
2833         return IntRange(C.getIntWidth(QualType(T, 0)), false);
2834
2835       unsigned NumPositive = Enum->getNumPositiveBits();
2836       unsigned NumNegative = Enum->getNumNegativeBits();
2837
2838       return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2839     }
2840
2841     const BuiltinType *BT = cast<BuiltinType>(T);
2842     assert(BT->isInteger());
2843
2844     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2845   }
2846
2847   /// Returns the "target" range of a canonical integral type, i.e.
2848   /// the range of values expressible in the type.
2849   ///
2850   /// This matches forValueOfCanonicalType except that enums have the
2851   /// full range of their type, not the range of their enumerators.
2852   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2853     assert(T->isCanonicalUnqualified());
2854
2855     if (const VectorType *VT = dyn_cast<VectorType>(T))
2856       T = VT->getElementType().getTypePtr();
2857     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2858       T = CT->getElementType().getTypePtr();
2859     if (const EnumType *ET = dyn_cast<EnumType>(T))
2860       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
2861
2862     const BuiltinType *BT = cast<BuiltinType>(T);
2863     assert(BT->isInteger());
2864
2865     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2866   }
2867
2868   /// Returns the supremum of two ranges: i.e. their conservative merge.
2869   static IntRange join(IntRange L, IntRange R) {
2870     return IntRange(std::max(L.Width, R.Width),
2871                     L.NonNegative && R.NonNegative);
2872   }
2873
2874   /// Returns the infinum of two ranges: i.e. their aggressive merge.
2875   static IntRange meet(IntRange L, IntRange R) {
2876     return IntRange(std::min(L.Width, R.Width),
2877                     L.NonNegative || R.NonNegative);
2878   }
2879 };
2880
2881 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2882   if (value.isSigned() && value.isNegative())
2883     return IntRange(value.getMinSignedBits(), false);
2884
2885   if (value.getBitWidth() > MaxWidth)
2886     value = value.trunc(MaxWidth);
2887
2888   // isNonNegative() just checks the sign bit without considering
2889   // signedness.
2890   return IntRange(value.getActiveBits(), true);
2891 }
2892
2893 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
2894                        unsigned MaxWidth) {
2895   if (result.isInt())
2896     return GetValueRange(C, result.getInt(), MaxWidth);
2897
2898   if (result.isVector()) {
2899     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2900     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2901       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2902       R = IntRange::join(R, El);
2903     }
2904     return R;
2905   }
2906
2907   if (result.isComplexInt()) {
2908     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2909     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2910     return IntRange::join(R, I);
2911   }
2912
2913   // This can happen with lossless casts to intptr_t of "based" lvalues.
2914   // Assume it might use arbitrary bits.
2915   // FIXME: The only reason we need to pass the type in here is to get
2916   // the sign right on this one case.  It would be nice if APValue
2917   // preserved this.
2918   assert(result.isLValue());
2919   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
2920 }
2921
2922 /// Pseudo-evaluate the given integer expression, estimating the
2923 /// range of values it might take.
2924 ///
2925 /// \param MaxWidth - the width to which the value will be truncated
2926 IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2927   E = E->IgnoreParens();
2928
2929   // Try a full evaluation first.
2930   Expr::EvalResult result;
2931   if (E->Evaluate(result, C))
2932     return GetValueRange(C, result.Val, E->getType(), MaxWidth);
2933
2934   // I think we only want to look through implicit casts here; if the
2935   // user has an explicit widening cast, we should treat the value as
2936   // being of the new, wider type.
2937   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
2938     if (CE->getCastKind() == CK_NoOp)
2939       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2940
2941     IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
2942
2943     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
2944
2945     // Assume that non-integer casts can span the full range of the type.
2946     if (!isIntegerCast)
2947       return OutputTypeRange;
2948
2949     IntRange SubRange
2950       = GetExprRange(C, CE->getSubExpr(),
2951                      std::min(MaxWidth, OutputTypeRange.Width));
2952
2953     // Bail out if the subexpr's range is as wide as the cast type.
2954     if (SubRange.Width >= OutputTypeRange.Width)
2955       return OutputTypeRange;
2956
2957     // Otherwise, we take the smaller width, and we're non-negative if
2958     // either the output type or the subexpr is.
2959     return IntRange(SubRange.Width,
2960                     SubRange.NonNegative || OutputTypeRange.NonNegative);
2961   }
2962
2963   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2964     // If we can fold the condition, just take that operand.
2965     bool CondResult;
2966     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2967       return GetExprRange(C, CondResult ? CO->getTrueExpr()
2968                                         : CO->getFalseExpr(),
2969                           MaxWidth);
2970
2971     // Otherwise, conservatively merge.
2972     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2973     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2974     return IntRange::join(L, R);
2975   }
2976
2977   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2978     switch (BO->getOpcode()) {
2979
2980     // Boolean-valued operations are single-bit and positive.
2981     case BO_LAnd:
2982     case BO_LOr:
2983     case BO_LT:
2984     case BO_GT:
2985     case BO_LE:
2986     case BO_GE:
2987     case BO_EQ:
2988     case BO_NE:
2989       return IntRange::forBoolType();
2990
2991     // The type of the assignments is the type of the LHS, so the RHS
2992     // is not necessarily the same type.
2993     case BO_MulAssign:
2994     case BO_DivAssign:
2995     case BO_RemAssign:
2996     case BO_AddAssign:
2997     case BO_SubAssign:
2998     case BO_XorAssign:
2999     case BO_OrAssign:
3000       // TODO: bitfields?
3001       return IntRange::forValueOfType(C, E->getType());
3002
3003     // Simple assignments just pass through the RHS, which will have
3004     // been coerced to the LHS type.
3005     case BO_Assign:
3006       // TODO: bitfields?
3007       return GetExprRange(C, BO->getRHS(), MaxWidth);
3008
3009     // Operations with opaque sources are black-listed.
3010     case BO_PtrMemD:
3011     case BO_PtrMemI:
3012       return IntRange::forValueOfType(C, E->getType());
3013
3014     // Bitwise-and uses the *infinum* of the two source ranges.
3015     case BO_And:
3016     case BO_AndAssign:
3017       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3018                             GetExprRange(C, BO->getRHS(), MaxWidth));
3019
3020     // Left shift gets black-listed based on a judgement call.
3021     case BO_Shl:
3022       // ...except that we want to treat '1 << (blah)' as logically
3023       // positive.  It's an important idiom.
3024       if (IntegerLiteral *I
3025             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3026         if (I->getValue() == 1) {
3027           IntRange R = IntRange::forValueOfType(C, E->getType());
3028           return IntRange(R.Width, /*NonNegative*/ true);
3029         }
3030       }
3031       // fallthrough
3032
3033     case BO_ShlAssign:
3034       return IntRange::forValueOfType(C, E->getType());
3035
3036     // Right shift by a constant can narrow its left argument.
3037     case BO_Shr:
3038     case BO_ShrAssign: {
3039       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3040
3041       // If the shift amount is a positive constant, drop the width by
3042       // that much.
3043       llvm::APSInt shift;
3044       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3045           shift.isNonNegative()) {
3046         unsigned zext = shift.getZExtValue();
3047         if (zext >= L.Width)
3048           L.Width = (L.NonNegative ? 0 : 1);
3049         else
3050           L.Width -= zext;
3051       }
3052
3053       return L;
3054     }
3055
3056     // Comma acts as its right operand.
3057     case BO_Comma:
3058       return GetExprRange(C, BO->getRHS(), MaxWidth);
3059
3060     // Black-list pointer subtractions.
3061     case BO_Sub:
3062       if (BO->getLHS()->getType()->isPointerType())
3063         return IntRange::forValueOfType(C, E->getType());
3064       break;
3065
3066     // The width of a division result is mostly determined by the size
3067     // of the LHS.
3068     case BO_Div: {
3069       // Don't 'pre-truncate' the operands.
3070       unsigned opWidth = C.getIntWidth(E->getType());
3071       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3072
3073       // If the divisor is constant, use that.
3074       llvm::APSInt divisor;
3075       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3076         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3077         if (log2 >= L.Width)
3078           L.Width = (L.NonNegative ? 0 : 1);
3079         else
3080           L.Width = std::min(L.Width - log2, MaxWidth);
3081         return L;
3082       }
3083
3084       // Otherwise, just use the LHS's width.
3085       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3086       return IntRange(L.Width, L.NonNegative && R.NonNegative);
3087     }
3088
3089     // The result of a remainder can't be larger than the result of
3090     // either side.
3091     case BO_Rem: {
3092       // Don't 'pre-truncate' the operands.
3093       unsigned opWidth = C.getIntWidth(E->getType());
3094       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3095       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3096
3097       IntRange meet = IntRange::meet(L, R);
3098       meet.Width = std::min(meet.Width, MaxWidth);
3099       return meet;
3100     }
3101
3102     // The default behavior is okay for these.
3103     case BO_Mul:
3104     case BO_Add:
3105     case BO_Xor:
3106     case BO_Or:
3107       break;
3108     }
3109
3110     // The default case is to treat the operation as if it were closed
3111     // on the narrowest type that encompasses both operands.
3112     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3113     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3114     return IntRange::join(L, R);
3115   }
3116
3117   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3118     switch (UO->getOpcode()) {
3119     // Boolean-valued operations are white-listed.
3120     case UO_LNot:
3121       return IntRange::forBoolType();
3122
3123     // Operations with opaque sources are black-listed.
3124     case UO_Deref:
3125     case UO_AddrOf: // should be impossible
3126       return IntRange::forValueOfType(C, E->getType());
3127
3128     default:
3129       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3130     }
3131   }
3132   
3133   if (dyn_cast<OffsetOfExpr>(E)) {
3134     IntRange::forValueOfType(C, E->getType());
3135   }
3136
3137   if (FieldDecl *BitField = E->getBitField())
3138     return IntRange(BitField->getBitWidthValue(C),
3139                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
3140
3141   return IntRange::forValueOfType(C, E->getType());
3142 }
3143
3144 IntRange GetExprRange(ASTContext &C, Expr *E) {
3145   return GetExprRange(C, E, C.getIntWidth(E->getType()));
3146 }
3147
3148 /// Checks whether the given value, which currently has the given
3149 /// source semantics, has the same value when coerced through the
3150 /// target semantics.
3151 bool IsSameFloatAfterCast(const llvm::APFloat &value,
3152                           const llvm::fltSemantics &Src,
3153                           const llvm::fltSemantics &Tgt) {
3154   llvm::APFloat truncated = value;
3155
3156   bool ignored;
3157   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3158   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3159
3160   return truncated.bitwiseIsEqual(value);
3161 }
3162
3163 /// Checks whether the given value, which currently has the given
3164 /// source semantics, has the same value when coerced through the
3165 /// target semantics.
3166 ///
3167 /// The value might be a vector of floats (or a complex number).
3168 bool IsSameFloatAfterCast(const APValue &value,
3169                           const llvm::fltSemantics &Src,
3170                           const llvm::fltSemantics &Tgt) {
3171   if (value.isFloat())
3172     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3173
3174   if (value.isVector()) {
3175     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3176       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3177         return false;
3178     return true;
3179   }
3180
3181   assert(value.isComplexFloat());
3182   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3183           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3184 }
3185
3186 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
3187
3188 static bool IsZero(Sema &S, Expr *E) {
3189   // Suppress cases where we are comparing against an enum constant.
3190   if (const DeclRefExpr *DR =
3191       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3192     if (isa<EnumConstantDecl>(DR->getDecl()))
3193       return false;
3194
3195   // Suppress cases where the '0' value is expanded from a macro.
3196   if (E->getLocStart().isMacroID())
3197     return false;
3198
3199   llvm::APSInt Value;
3200   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3201 }
3202
3203 static bool HasEnumType(Expr *E) {
3204   // Strip off implicit integral promotions.
3205   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3206     if (ICE->getCastKind() != CK_IntegralCast &&
3207         ICE->getCastKind() != CK_NoOp)
3208       break;
3209     E = ICE->getSubExpr();
3210   }
3211
3212   return E->getType()->isEnumeralType();
3213 }
3214
3215 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
3216   BinaryOperatorKind op = E->getOpcode();
3217   if (E->isValueDependent())
3218     return;
3219
3220   if (op == BO_LT && IsZero(S, E->getRHS())) {
3221     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3222       << "< 0" << "false" << HasEnumType(E->getLHS())
3223       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3224   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
3225     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3226       << ">= 0" << "true" << HasEnumType(E->getLHS())
3227       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3228   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
3229     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3230       << "0 >" << "false" << HasEnumType(E->getRHS())
3231       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3232   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
3233     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3234       << "0 <=" << "true" << HasEnumType(E->getRHS())
3235       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3236   }
3237 }
3238
3239 /// Analyze the operands of the given comparison.  Implements the
3240 /// fallback case from AnalyzeComparison.
3241 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
3242   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3243   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3244 }
3245
3246 /// \brief Implements -Wsign-compare.
3247 ///
3248 /// \param E the binary operator to check for warnings
3249 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3250   // The type the comparison is being performed in.
3251   QualType T = E->getLHS()->getType();
3252   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3253          && "comparison with mismatched types");
3254
3255   // We don't do anything special if this isn't an unsigned integral
3256   // comparison:  we're only interested in integral comparisons, and
3257   // signed comparisons only happen in cases we don't care to warn about.
3258   //
3259   // We also don't care about value-dependent expressions or expressions
3260   // whose result is a constant.
3261   if (!T->hasUnsignedIntegerRepresentation()
3262       || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
3263     return AnalyzeImpConvsInComparison(S, E);
3264
3265   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3266   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
3267
3268   // Check to see if one of the (unmodified) operands is of different
3269   // signedness.
3270   Expr *signedOperand, *unsignedOperand;
3271   if (LHS->getType()->hasSignedIntegerRepresentation()) {
3272     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
3273            "unsigned comparison between two signed integer expressions?");
3274     signedOperand = LHS;
3275     unsignedOperand = RHS;
3276   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3277     signedOperand = RHS;
3278     unsignedOperand = LHS;
3279   } else {
3280     CheckTrivialUnsignedComparison(S, E);
3281     return AnalyzeImpConvsInComparison(S, E);
3282   }
3283
3284   // Otherwise, calculate the effective range of the signed operand.
3285   IntRange signedRange = GetExprRange(S.Context, signedOperand);
3286
3287   // Go ahead and analyze implicit conversions in the operands.  Note
3288   // that we skip the implicit conversions on both sides.
3289   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3290   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
3291
3292   // If the signed range is non-negative, -Wsign-compare won't fire,
3293   // but we should still check for comparisons which are always true
3294   // or false.
3295   if (signedRange.NonNegative)
3296     return CheckTrivialUnsignedComparison(S, E);
3297
3298   // For (in)equality comparisons, if the unsigned operand is a
3299   // constant which cannot collide with a overflowed signed operand,
3300   // then reinterpreting the signed operand as unsigned will not
3301   // change the result of the comparison.
3302   if (E->isEqualityOp()) {
3303     unsigned comparisonWidth = S.Context.getIntWidth(T);
3304     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
3305
3306     // We should never be unable to prove that the unsigned operand is
3307     // non-negative.
3308     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3309
3310     if (unsignedRange.Width < comparisonWidth)
3311       return;
3312   }
3313
3314   S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3315     << LHS->getType() << RHS->getType()
3316     << LHS->getSourceRange() << RHS->getSourceRange();
3317 }
3318
3319 /// Analyzes an attempt to assign the given value to a bitfield.
3320 ///
3321 /// Returns true if there was something fishy about the attempt.
3322 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3323                                SourceLocation InitLoc) {
3324   assert(Bitfield->isBitField());
3325   if (Bitfield->isInvalidDecl())
3326     return false;
3327
3328   // White-list bool bitfields.
3329   if (Bitfield->getType()->isBooleanType())
3330     return false;
3331
3332   // Ignore value- or type-dependent expressions.
3333   if (Bitfield->getBitWidth()->isValueDependent() ||
3334       Bitfield->getBitWidth()->isTypeDependent() ||
3335       Init->isValueDependent() ||
3336       Init->isTypeDependent())
3337     return false;
3338
3339   Expr *OriginalInit = Init->IgnoreParenImpCasts();
3340
3341   Expr::EvalResult InitValue;
3342   if (!OriginalInit->Evaluate(InitValue, S.Context) ||
3343       !InitValue.Val.isInt())
3344     return false;
3345
3346   const llvm::APSInt &Value = InitValue.Val.getInt();
3347   unsigned OriginalWidth = Value.getBitWidth();
3348   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
3349
3350   if (OriginalWidth <= FieldWidth)
3351     return false;
3352
3353   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
3354
3355   // It's fairly common to write values into signed bitfields
3356   // that, if sign-extended, would end up becoming a different
3357   // value.  We don't want to warn about that.
3358   if (Value.isSigned() && Value.isNegative())
3359     TruncatedValue = TruncatedValue.sext(OriginalWidth);
3360   else
3361     TruncatedValue = TruncatedValue.zext(OriginalWidth);
3362
3363   if (Value == TruncatedValue)
3364     return false;
3365
3366   std::string PrettyValue = Value.toString(10);
3367   std::string PrettyTrunc = TruncatedValue.toString(10);
3368
3369   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3370     << PrettyValue << PrettyTrunc << OriginalInit->getType()
3371     << Init->getSourceRange();
3372
3373   return true;
3374 }
3375
3376 /// Analyze the given simple or compound assignment for warning-worthy
3377 /// operations.
3378 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3379   // Just recurse on the LHS.
3380   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3381
3382   // We want to recurse on the RHS as normal unless we're assigning to
3383   // a bitfield.
3384   if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
3385     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3386                                   E->getOperatorLoc())) {
3387       // Recurse, ignoring any implicit conversions on the RHS.
3388       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3389                                         E->getOperatorLoc());
3390     }
3391   }
3392
3393   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3394 }
3395
3396 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3397 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 
3398                      SourceLocation CContext, unsigned diag) {
3399   S.Diag(E->getExprLoc(), diag)
3400     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3401 }
3402
3403 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3404 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3405                      unsigned diag) {
3406   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3407 }
3408
3409 /// Diagnose an implicit cast from a literal expression. Does not warn when the
3410 /// cast wouldn't lose information.
3411 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3412                                     SourceLocation CContext) {
3413   // Try to convert the literal exactly to an integer. If we can, don't warn.
3414   bool isExact = false;
3415   const llvm::APFloat &Value = FL->getValue();
3416   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3417                             T->hasUnsignedIntegerRepresentation());
3418   if (Value.convertToInteger(IntegerValue,
3419                              llvm::APFloat::rmTowardZero, &isExact)
3420       == llvm::APFloat::opOK && isExact)
3421     return;
3422
3423   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3424     << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3425 }
3426
3427 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3428   if (!Range.Width) return "0";
3429
3430   llvm::APSInt ValueInRange = Value;
3431   ValueInRange.setIsSigned(!Range.NonNegative);
3432   ValueInRange = ValueInRange.trunc(Range.Width);
3433   return ValueInRange.toString(10);
3434 }
3435
3436 static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3437   SourceManager &smgr = S.Context.getSourceManager();
3438   return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3439 }
3440
3441 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
3442                              SourceLocation CC, bool *ICContext = 0) {
3443   if (E->isTypeDependent() || E->isValueDependent()) return;
3444
3445   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3446   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3447   if (Source == Target) return;
3448   if (Target->isDependentType()) return;
3449
3450   // If the conversion context location is invalid don't complain. We also
3451   // don't want to emit a warning if the issue occurs from the expansion of
3452   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3453   // delay this check as long as possible. Once we detect we are in that
3454   // scenario, we just return.
3455   if (CC.isInvalid())
3456     return;
3457
3458   // Diagnose implicit casts to bool.
3459   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3460     if (isa<StringLiteral>(E))
3461       // Warn on string literal to bool.  Checks for string literals in logical
3462       // expressions, for instances, assert(0 && "error here"), is prevented
3463       // by a check in AnalyzeImplicitConversions().
3464       return DiagnoseImpCast(S, E, T, CC,
3465                              diag::warn_impcast_string_literal_to_bool);
3466     return; // Other casts to bool are not checked.
3467   }
3468
3469   // Strip vector types.
3470   if (isa<VectorType>(Source)) {
3471     if (!isa<VectorType>(Target)) {
3472       if (isFromSystemMacro(S, CC))
3473         return;
3474       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
3475     }
3476     
3477     // If the vector cast is cast between two vectors of the same size, it is
3478     // a bitcast, not a conversion.
3479     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3480       return;
3481
3482     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3483     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3484   }
3485
3486   // Strip complex types.
3487   if (isa<ComplexType>(Source)) {
3488     if (!isa<ComplexType>(Target)) {
3489       if (isFromSystemMacro(S, CC))
3490         return;
3491
3492       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
3493     }
3494
3495     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3496     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3497   }
3498
3499   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3500   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3501
3502   // If the source is floating point...
3503   if (SourceBT && SourceBT->isFloatingPoint()) {
3504     // ...and the target is floating point...
3505     if (TargetBT && TargetBT->isFloatingPoint()) {
3506       // ...then warn if we're dropping FP rank.
3507
3508       // Builtin FP kinds are ordered by increasing FP rank.
3509       if (SourceBT->getKind() > TargetBT->getKind()) {
3510         // Don't warn about float constants that are precisely
3511         // representable in the target type.
3512         Expr::EvalResult result;
3513         if (E->Evaluate(result, S.Context)) {
3514           // Value might be a float, a float vector, or a float complex.
3515           if (IsSameFloatAfterCast(result.Val,
3516                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3517                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
3518             return;
3519         }
3520
3521         if (isFromSystemMacro(S, CC))
3522           return;
3523
3524         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
3525       }
3526       return;
3527     }
3528
3529     // If the target is integral, always warn.    
3530     if ((TargetBT && TargetBT->isInteger())) {
3531       if (isFromSystemMacro(S, CC))
3532         return;
3533       
3534       Expr *InnerE = E->IgnoreParenImpCasts();
3535       // We also want to warn on, e.g., "int i = -1.234"
3536       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3537         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3538           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3539
3540       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3541         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
3542       } else {
3543         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3544       }
3545     }
3546
3547     return;
3548   }
3549
3550   if (!Source->isIntegerType() || !Target->isIntegerType())
3551     return;
3552
3553   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3554            == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3555     S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3556         << E->getSourceRange() << clang::SourceRange(CC);
3557     return;
3558   }
3559
3560   IntRange SourceRange = GetExprRange(S.Context, E);
3561   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
3562
3563   if (SourceRange.Width > TargetRange.Width) {
3564     // If the source is a constant, use a default-on diagnostic.
3565     // TODO: this should happen for bitfield stores, too.
3566     llvm::APSInt Value(32);
3567     if (E->isIntegerConstantExpr(Value, S.Context)) {
3568       if (isFromSystemMacro(S, CC))
3569         return;
3570
3571       std::string PrettySourceValue = Value.toString(10);
3572       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3573
3574       S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3575         << PrettySourceValue << PrettyTargetValue
3576         << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3577       return;
3578     }
3579
3580     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
3581     if (isFromSystemMacro(S, CC))
3582       return;
3583     
3584     if (SourceRange.Width == 64 && TargetRange.Width == 32)
3585       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3586     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
3587   }
3588
3589   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3590       (!TargetRange.NonNegative && SourceRange.NonNegative &&
3591        SourceRange.Width == TargetRange.Width)) {
3592         
3593     if (isFromSystemMacro(S, CC))
3594       return;
3595
3596     unsigned DiagID = diag::warn_impcast_integer_sign;
3597
3598     // Traditionally, gcc has warned about this under -Wsign-compare.
3599     // We also want to warn about it in -Wconversion.
3600     // So if -Wconversion is off, use a completely identical diagnostic
3601     // in the sign-compare group.
3602     // The conditional-checking code will 
3603     if (ICContext) {
3604       DiagID = diag::warn_impcast_integer_sign_conditional;
3605       *ICContext = true;
3606     }
3607
3608     return DiagnoseImpCast(S, E, T, CC, DiagID);
3609   }
3610
3611   // Diagnose conversions between different enumeration types.
3612   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3613   // type, to give us better diagnostics.
3614   QualType SourceType = E->getType();
3615   if (!S.getLangOptions().CPlusPlus) {
3616     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3617       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3618         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3619         SourceType = S.Context.getTypeDeclType(Enum);
3620         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3621       }
3622   }
3623   
3624   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3625     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3626       if ((SourceEnum->getDecl()->getIdentifier() || 
3627            SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3628           (TargetEnum->getDecl()->getIdentifier() ||
3629            TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3630           SourceEnum != TargetEnum) {
3631         if (isFromSystemMacro(S, CC))
3632           return;
3633
3634         return DiagnoseImpCast(S, E, SourceType, T, CC, 
3635                                diag::warn_impcast_different_enum_types);
3636       }
3637   
3638   return;
3639 }
3640
3641 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3642
3643 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
3644                              SourceLocation CC, bool &ICContext) {
3645   E = E->IgnoreParenImpCasts();
3646
3647   if (isa<ConditionalOperator>(E))
3648     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3649
3650   AnalyzeImplicitConversions(S, E, CC);
3651   if (E->getType() != T)
3652     return CheckImplicitConversion(S, E, T, CC, &ICContext);
3653   return;
3654 }
3655
3656 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
3657   SourceLocation CC = E->getQuestionLoc();
3658
3659   AnalyzeImplicitConversions(S, E->getCond(), CC);
3660
3661   bool Suspicious = false;
3662   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3663   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
3664
3665   // If -Wconversion would have warned about either of the candidates
3666   // for a signedness conversion to the context type...
3667   if (!Suspicious) return;
3668
3669   // ...but it's currently ignored...
3670   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3671                                  CC))
3672     return;
3673
3674   // ...then check whether it would have warned about either of the
3675   // candidates for a signedness conversion to the condition type.
3676   if (E->getType() == T) return;
3677  
3678   Suspicious = false;
3679   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3680                           E->getType(), CC, &Suspicious);
3681   if (!Suspicious)
3682     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
3683                             E->getType(), CC, &Suspicious);
3684 }
3685
3686 /// AnalyzeImplicitConversions - Find and report any interesting
3687 /// implicit conversions in the given expression.  There are a couple
3688 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
3689 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
3690   QualType T = OrigE->getType();
3691   Expr *E = OrigE->IgnoreParenImpCasts();
3692
3693   if (E->isTypeDependent() || E->isValueDependent())
3694     return;
3695
3696   // For conditional operators, we analyze the arguments as if they
3697   // were being fed directly into the output.
3698   if (isa<ConditionalOperator>(E)) {
3699     ConditionalOperator *CO = cast<ConditionalOperator>(E);
3700     CheckConditionalOperator(S, CO, T);
3701     return;
3702   }
3703
3704   // Go ahead and check any implicit conversions we might have skipped.
3705   // The non-canonical typecheck is just an optimization;
3706   // CheckImplicitConversion will filter out dead implicit conversions.
3707   if (E->getType() != T)
3708     CheckImplicitConversion(S, E, T, CC);
3709
3710   // Now continue drilling into this expression.
3711
3712   // Skip past explicit casts.
3713   if (isa<ExplicitCastExpr>(E)) {
3714     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
3715     return AnalyzeImplicitConversions(S, E, CC);
3716   }
3717
3718   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3719     // Do a somewhat different check with comparison operators.
3720     if (BO->isComparisonOp())
3721       return AnalyzeComparison(S, BO);
3722
3723     // And with assignments and compound assignments.
3724     if (BO->isAssignmentOp())
3725       return AnalyzeAssignment(S, BO);
3726   }
3727
3728   // These break the otherwise-useful invariant below.  Fortunately,
3729   // we don't really need to recurse into them, because any internal
3730   // expressions should have been analyzed already when they were
3731   // built into statements.
3732   if (isa<StmtExpr>(E)) return;
3733
3734   // Don't descend into unevaluated contexts.
3735   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
3736
3737   // Now just recurse over the expression's children.
3738   CC = E->getExprLoc();
3739   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3740   bool IsLogicalOperator = BO && BO->isLogicalOp();
3741   for (Stmt::child_range I = E->children(); I; ++I) {
3742     Expr *ChildExpr = cast<Expr>(*I);
3743     if (IsLogicalOperator &&
3744         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3745       // Ignore checking string literals that are in logical operators.
3746       continue;
3747     AnalyzeImplicitConversions(S, ChildExpr, CC);
3748   }
3749 }
3750
3751 } // end anonymous namespace
3752
3753 /// Diagnoses "dangerous" implicit conversions within the given
3754 /// expression (which is a full expression).  Implements -Wconversion
3755 /// and -Wsign-compare.
3756 ///
3757 /// \param CC the "context" location of the implicit conversion, i.e.
3758 ///   the most location of the syntactic entity requiring the implicit
3759 ///   conversion
3760 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
3761   // Don't diagnose in unevaluated contexts.
3762   if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3763     return;
3764
3765   // Don't diagnose for value- or type-dependent expressions.
3766   if (E->isTypeDependent() || E->isValueDependent())
3767     return;
3768
3769   // Check for array bounds violations in cases where the check isn't triggered
3770   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3771   // ArraySubscriptExpr is on the RHS of a variable initialization.
3772   CheckArrayAccess(E);
3773
3774   // This is not the right CC for (e.g.) a variable initialization.
3775   AnalyzeImplicitConversions(*this, E, CC);
3776 }
3777
3778 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3779                                        FieldDecl *BitField,
3780                                        Expr *Init) {
3781   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3782 }
3783
3784 /// CheckParmsForFunctionDef - Check that the parameters of the given
3785 /// function are appropriate for the definition of a function. This
3786 /// takes care of any checks that cannot be performed on the
3787 /// declaration itself, e.g., that the types of each of the function
3788 /// parameters are complete.
3789 bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3790                                     bool CheckParameterNames) {
3791   bool HasInvalidParm = false;
3792   for (; P != PEnd; ++P) {
3793     ParmVarDecl *Param = *P;
3794     
3795     // C99 6.7.5.3p4: the parameters in a parameter type list in a
3796     // function declarator that is part of a function definition of
3797     // that function shall not have incomplete type.
3798     //
3799     // This is also C++ [dcl.fct]p6.
3800     if (!Param->isInvalidDecl() &&
3801         RequireCompleteType(Param->getLocation(), Param->getType(),
3802                                diag::err_typecheck_decl_incomplete_type)) {
3803       Param->setInvalidDecl();
3804       HasInvalidParm = true;
3805     }
3806
3807     // C99 6.9.1p5: If the declarator includes a parameter type list, the
3808     // declaration of each parameter shall include an identifier.
3809     if (CheckParameterNames &&
3810         Param->getIdentifier() == 0 &&
3811         !Param->isImplicit() &&
3812         !getLangOptions().CPlusPlus)
3813       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
3814
3815     // C99 6.7.5.3p12:
3816     //   If the function declarator is not part of a definition of that
3817     //   function, parameters may have incomplete type and may use the [*]
3818     //   notation in their sequences of declarator specifiers to specify
3819     //   variable length array types.
3820     QualType PType = Param->getOriginalType();
3821     if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3822       if (AT->getSizeModifier() == ArrayType::Star) {
3823         // FIXME: This diagnosic should point the the '[*]' if source-location
3824         // information is added for it.
3825         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3826       }
3827     }
3828   }
3829
3830   return HasInvalidParm;
3831 }
3832
3833 /// CheckCastAlign - Implements -Wcast-align, which warns when a
3834 /// pointer cast increases the alignment requirements.
3835 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3836   // This is actually a lot of work to potentially be doing on every
3837   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3838   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3839                                           TRange.getBegin())
3840         == DiagnosticsEngine::Ignored)
3841     return;
3842
3843   // Ignore dependent types.
3844   if (T->isDependentType() || Op->getType()->isDependentType())
3845     return;
3846
3847   // Require that the destination be a pointer type.
3848   const PointerType *DestPtr = T->getAs<PointerType>();
3849   if (!DestPtr) return;
3850
3851   // If the destination has alignment 1, we're done.
3852   QualType DestPointee = DestPtr->getPointeeType();
3853   if (DestPointee->isIncompleteType()) return;
3854   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3855   if (DestAlign.isOne()) return;
3856
3857   // Require that the source be a pointer type.
3858   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3859   if (!SrcPtr) return;
3860   QualType SrcPointee = SrcPtr->getPointeeType();
3861
3862   // Whitelist casts from cv void*.  We already implicitly
3863   // whitelisted casts to cv void*, since they have alignment 1.
3864   // Also whitelist casts involving incomplete types, which implicitly
3865   // includes 'void'.
3866   if (SrcPointee->isIncompleteType()) return;
3867
3868   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3869   if (SrcAlign >= DestAlign) return;
3870
3871   Diag(TRange.getBegin(), diag::warn_cast_align)
3872     << Op->getType() << T
3873     << static_cast<unsigned>(SrcAlign.getQuantity())
3874     << static_cast<unsigned>(DestAlign.getQuantity())
3875     << TRange << Op->getSourceRange();
3876 }
3877
3878 static const Type* getElementType(const Expr *BaseExpr) {
3879   const Type* EltType = BaseExpr->getType().getTypePtr();
3880   if (EltType->isAnyPointerType())
3881     return EltType->getPointeeType().getTypePtr();
3882   else if (EltType->isArrayType())
3883     return EltType->getBaseElementTypeUnsafe();
3884   return EltType;
3885 }
3886
3887 /// \brief Check whether this array fits the idiom of a size-one tail padded
3888 /// array member of a struct.
3889 ///
3890 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
3891 /// commonly used to emulate flexible arrays in C89 code.
3892 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3893                                     const NamedDecl *ND) {
3894   if (Size != 1 || !ND) return false;
3895
3896   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3897   if (!FD) return false;
3898
3899   // Don't consider sizes resulting from macro expansions or template argument
3900   // substitution to form C89 tail-padded arrays.
3901   ConstantArrayTypeLoc TL =
3902     cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3903   const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3904   if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3905     return false;
3906
3907   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3908   if (!RD || !RD->isStruct())
3909     return false;
3910
3911   // See if this is the last field decl in the record.
3912   const Decl *D = FD;
3913   while ((D = D->getNextDeclInContext()))
3914     if (isa<FieldDecl>(D))
3915       return false;
3916   return true;
3917 }
3918
3919 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3920                             bool isSubscript, bool AllowOnePastEnd) {
3921   const Type* EffectiveType = getElementType(BaseExpr);
3922   BaseExpr = BaseExpr->IgnoreParenCasts();
3923   IndexExpr = IndexExpr->IgnoreParenCasts();
3924
3925   const ConstantArrayType *ArrayTy =
3926     Context.getAsConstantArrayType(BaseExpr->getType());
3927   if (!ArrayTy)
3928     return;
3929
3930   if (IndexExpr->isValueDependent())
3931     return;
3932   llvm::APSInt index;
3933   if (!IndexExpr->isIntegerConstantExpr(index, Context))
3934     return;
3935
3936   const NamedDecl *ND = NULL;
3937   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3938     ND = dyn_cast<NamedDecl>(DRE->getDecl());
3939   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3940     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3941
3942   if (index.isUnsigned() || !index.isNegative()) {
3943     llvm::APInt size = ArrayTy->getSize();
3944     if (!size.isStrictlyPositive())
3945       return;
3946
3947     const Type* BaseType = getElementType(BaseExpr);
3948     if (BaseType != EffectiveType) {
3949       // Make sure we're comparing apples to apples when comparing index to size
3950       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3951       uint64_t array_typesize = Context.getTypeSize(BaseType);
3952       // Handle ptrarith_typesize being zero, such as when casting to void*
3953       if (!ptrarith_typesize) ptrarith_typesize = 1;
3954       if (ptrarith_typesize != array_typesize) {
3955         // There's a cast to a different size type involved
3956         uint64_t ratio = array_typesize / ptrarith_typesize;
3957         // TODO: Be smarter about handling cases where array_typesize is not a
3958         // multiple of ptrarith_typesize
3959         if (ptrarith_typesize * ratio == array_typesize)
3960           size *= llvm::APInt(size.getBitWidth(), ratio);
3961       }
3962     }
3963
3964     if (size.getBitWidth() > index.getBitWidth())
3965       index = index.sext(size.getBitWidth());
3966     else if (size.getBitWidth() < index.getBitWidth())
3967       size = size.sext(index.getBitWidth());
3968
3969     // For array subscripting the index must be less than size, but for pointer
3970     // arithmetic also allow the index (offset) to be equal to size since
3971     // computing the next address after the end of the array is legal and
3972     // commonly done e.g. in C++ iterators and range-based for loops.
3973     if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
3974       return;
3975
3976     // Also don't warn for arrays of size 1 which are members of some
3977     // structure. These are often used to approximate flexible arrays in C89
3978     // code.
3979     if (IsTailPaddedMemberArray(*this, size, ND))
3980       return;
3981
3982     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3983     if (isSubscript)
3984       DiagID = diag::warn_array_index_exceeds_bounds;
3985
3986     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3987                         PDiag(DiagID) << index.toString(10, true)
3988                           << size.toString(10, true)
3989                           << (unsigned)size.getLimitedValue(~0U)
3990                           << IndexExpr->getSourceRange());
3991   } else {
3992     unsigned DiagID = diag::warn_array_index_precedes_bounds;
3993     if (!isSubscript) {
3994       DiagID = diag::warn_ptr_arith_precedes_bounds;
3995       if (index.isNegative()) index = -index;
3996     }
3997
3998     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3999                         PDiag(DiagID) << index.toString(10, true)
4000                           << IndexExpr->getSourceRange());
4001   }
4002
4003   if (ND)
4004     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4005                         PDiag(diag::note_array_index_out_of_bounds)
4006                           << ND->getDeclName());
4007 }
4008
4009 void Sema::CheckArrayAccess(const Expr *expr) {
4010   int AllowOnePastEnd = 0;
4011   while (expr) {
4012     expr = expr->IgnoreParenImpCasts();
4013     switch (expr->getStmtClass()) {
4014       case Stmt::ArraySubscriptExprClass: {
4015         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4016         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4017                          AllowOnePastEnd > 0);
4018         return;
4019       }
4020       case Stmt::UnaryOperatorClass: {
4021         // Only unwrap the * and & unary operators
4022         const UnaryOperator *UO = cast<UnaryOperator>(expr);
4023         expr = UO->getSubExpr();
4024         switch (UO->getOpcode()) {
4025           case UO_AddrOf:
4026             AllowOnePastEnd++;
4027             break;
4028           case UO_Deref:
4029             AllowOnePastEnd--;
4030             break;
4031           default:
4032             return;
4033         }
4034         break;
4035       }
4036       case Stmt::ConditionalOperatorClass: {
4037         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4038         if (const Expr *lhs = cond->getLHS())
4039           CheckArrayAccess(lhs);
4040         if (const Expr *rhs = cond->getRHS())
4041           CheckArrayAccess(rhs);
4042         return;
4043       }
4044       default:
4045         return;
4046     }
4047   }
4048 }
4049
4050 //===--- CHECK: Objective-C retain cycles ----------------------------------//
4051
4052 namespace {
4053   struct RetainCycleOwner {
4054     RetainCycleOwner() : Variable(0), Indirect(false) {}
4055     VarDecl *Variable;
4056     SourceRange Range;
4057     SourceLocation Loc;
4058     bool Indirect;
4059
4060     void setLocsFrom(Expr *e) {
4061       Loc = e->getExprLoc();
4062       Range = e->getSourceRange();
4063     }
4064   };
4065 }
4066
4067 /// Consider whether capturing the given variable can possibly lead to
4068 /// a retain cycle.
4069 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4070   // In ARC, it's captured strongly iff the variable has __strong
4071   // lifetime.  In MRR, it's captured strongly if the variable is
4072   // __block and has an appropriate type.
4073   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4074     return false;
4075
4076   owner.Variable = var;
4077   owner.setLocsFrom(ref);
4078   return true;
4079 }
4080
4081 static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4082   while (true) {
4083     e = e->IgnoreParens();
4084     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4085       switch (cast->getCastKind()) {
4086       case CK_BitCast:
4087       case CK_LValueBitCast:
4088       case CK_LValueToRValue:
4089       case CK_ARCReclaimReturnedObject:
4090         e = cast->getSubExpr();
4091         continue;
4092
4093       case CK_GetObjCProperty: {
4094         // Bail out if this isn't a strong explicit property.
4095         const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
4096         if (pre->isImplicitProperty()) return false;
4097         ObjCPropertyDecl *property = pre->getExplicitProperty();
4098         if (!property->isRetaining() &&
4099             !(property->getPropertyIvarDecl() &&
4100               property->getPropertyIvarDecl()->getType()
4101                 .getObjCLifetime() == Qualifiers::OCL_Strong))
4102           return false;
4103
4104         owner.Indirect = true;
4105         e = const_cast<Expr*>(pre->getBase());
4106         continue;
4107       }
4108         
4109       default:
4110         return false;
4111       }
4112     }
4113
4114     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4115       ObjCIvarDecl *ivar = ref->getDecl();
4116       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4117         return false;
4118
4119       // Try to find a retain cycle in the base.
4120       if (!findRetainCycleOwner(ref->getBase(), owner))
4121         return false;
4122
4123       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4124       owner.Indirect = true;
4125       return true;
4126     }
4127
4128     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4129       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4130       if (!var) return false;
4131       return considerVariable(var, ref, owner);
4132     }
4133
4134     if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4135       owner.Variable = ref->getDecl();
4136       owner.setLocsFrom(ref);
4137       return true;
4138     }
4139
4140     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4141       if (member->isArrow()) return false;
4142
4143       // Don't count this as an indirect ownership.
4144       e = member->getBase();
4145       continue;
4146     }
4147
4148     // Array ivars?
4149
4150     return false;
4151   }
4152 }
4153
4154 namespace {
4155   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4156     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4157       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4158         Variable(variable), Capturer(0) {}
4159
4160     VarDecl *Variable;
4161     Expr *Capturer;
4162
4163     void VisitDeclRefExpr(DeclRefExpr *ref) {
4164       if (ref->getDecl() == Variable && !Capturer)
4165         Capturer = ref;
4166     }
4167
4168     void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4169       if (ref->getDecl() == Variable && !Capturer)
4170         Capturer = ref;
4171     }
4172
4173     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4174       if (Capturer) return;
4175       Visit(ref->getBase());
4176       if (Capturer && ref->isFreeIvar())
4177         Capturer = ref;
4178     }
4179
4180     void VisitBlockExpr(BlockExpr *block) {
4181       // Look inside nested blocks 
4182       if (block->getBlockDecl()->capturesVariable(Variable))
4183         Visit(block->getBlockDecl()->getBody());
4184     }
4185   };
4186 }
4187
4188 /// Check whether the given argument is a block which captures a
4189 /// variable.
4190 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4191   assert(owner.Variable && owner.Loc.isValid());
4192
4193   e = e->IgnoreParenCasts();
4194   BlockExpr *block = dyn_cast<BlockExpr>(e);
4195   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4196     return 0;
4197
4198   FindCaptureVisitor visitor(S.Context, owner.Variable);
4199   visitor.Visit(block->getBlockDecl()->getBody());
4200   return visitor.Capturer;
4201 }
4202
4203 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4204                                 RetainCycleOwner &owner) {
4205   assert(capturer);
4206   assert(owner.Variable && owner.Loc.isValid());
4207
4208   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4209     << owner.Variable << capturer->getSourceRange();
4210   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4211     << owner.Indirect << owner.Range;
4212 }
4213
4214 /// Check for a keyword selector that starts with the word 'add' or
4215 /// 'set'.
4216 static bool isSetterLikeSelector(Selector sel) {
4217   if (sel.isUnarySelector()) return false;
4218
4219   StringRef str = sel.getNameForSlot(0);
4220   while (!str.empty() && str.front() == '_') str = str.substr(1);
4221   if (str.startswith("set") || str.startswith("add"))
4222     str = str.substr(3);
4223   else
4224     return false;
4225
4226   if (str.empty()) return true;
4227   return !islower(str.front());
4228 }
4229
4230 /// Check a message send to see if it's likely to cause a retain cycle.
4231 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4232   // Only check instance methods whose selector looks like a setter.
4233   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4234     return;
4235
4236   // Try to find a variable that the receiver is strongly owned by.
4237   RetainCycleOwner owner;
4238   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4239     if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4240       return;
4241   } else {
4242     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4243     owner.Variable = getCurMethodDecl()->getSelfDecl();
4244     owner.Loc = msg->getSuperLoc();
4245     owner.Range = msg->getSuperLoc();
4246   }
4247
4248   // Check whether the receiver is captured by any of the arguments.
4249   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4250     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4251       return diagnoseRetainCycle(*this, capturer, owner);
4252 }
4253
4254 /// Check a property assign to see if it's likely to cause a retain cycle.
4255 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4256   RetainCycleOwner owner;
4257   if (!findRetainCycleOwner(receiver, owner))
4258     return;
4259
4260   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4261     diagnoseRetainCycle(*this, capturer, owner);
4262 }
4263
4264 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
4265                               QualType LHS, Expr *RHS) {
4266   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4267   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
4268     return false;
4269   // strip off any implicit cast added to get to the one arc-specific
4270   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4271     if (cast->getCastKind() == CK_ARCConsumeObject) {
4272       Diag(Loc, diag::warn_arc_retained_assign)
4273         << (LT == Qualifiers::OCL_ExplicitNone) 
4274         << RHS->getSourceRange();
4275       return true;
4276     }
4277     RHS = cast->getSubExpr();
4278   }
4279   return false;
4280 }
4281
4282 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4283                               Expr *LHS, Expr *RHS) {
4284   QualType LHSType = LHS->getType();
4285   if (checkUnsafeAssigns(Loc, LHSType, RHS))
4286     return;
4287   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4288   // FIXME. Check for other life times.
4289   if (LT != Qualifiers::OCL_None)
4290     return;
4291   
4292   if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4293     if (PRE->isImplicitProperty())
4294       return;
4295     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4296     if (!PD)
4297       return;
4298     
4299     unsigned Attributes = PD->getPropertyAttributes();
4300     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4301       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4302         if (cast->getCastKind() == CK_ARCConsumeObject) {
4303           Diag(Loc, diag::warn_arc_retained_property_assign)
4304           << RHS->getSourceRange();
4305           return;
4306         }
4307         RHS = cast->getSubExpr();
4308       }
4309   }
4310 }