Sema.cpp revision b9c142fd0ad32124fe670fc6455ec5229c49eaa6
1//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
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 the actions class which performs semantic analysis and
11// builds an AST out of a parse stream.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/APFloat.h"
18#include "clang/AST/ASTConsumer.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/TargetInfo.h"
25using namespace clang;
26
27/// Determines whether we should have an a.k.a. clause when
28/// pretty-printing a type.  There are three main criteria:
29///
30/// 1) Some types provide very minimal sugar that doesn't impede the
31///    user's understanding --- for example, elaborated type
32///    specifiers.  If this is all the sugar we see, we don't want an
33///    a.k.a. clause.
34/// 2) Some types are technically sugared but are much more familiar
35///    when seen in their sugared form --- for example, va_list,
36///    vector types, and the magic Objective C types.  We don't
37///    want to desugar these, even if we do produce an a.k.a. clause.
38/// 3) Some types may have already been desugared previously in this diagnostic.
39///    if this is the case, doing another "aka" would just be clutter.
40///
41static bool ShouldAKA(ASTContext &Context, QualType QT,
42                      const Diagnostic::ArgumentValue *PrevArgs,
43                      unsigned NumPrevArgs,
44                      QualType &DesugaredQT) {
45  QualType InputTy = QT;
46
47  bool AKA = false;
48  QualifierCollector Qc;
49
50  while (true) {
51    const Type *Ty = Qc.strip(QT);
52
53    // Don't aka just because we saw an elaborated type...
54    if (isa<ElaboratedType>(Ty)) {
55      QT = cast<ElaboratedType>(Ty)->desugar();
56      continue;
57    }
58
59    // ...or a qualified name type...
60    if (isa<QualifiedNameType>(Ty)) {
61      QT = cast<QualifiedNameType>(Ty)->desugar();
62      continue;
63    }
64
65    // ...or a substituted template type parameter.
66    if (isa<SubstTemplateTypeParmType>(Ty)) {
67      QT = cast<SubstTemplateTypeParmType>(Ty)->desugar();
68      continue;
69    }
70
71    // Don't desugar template specializations.
72    if (isa<TemplateSpecializationType>(Ty))
73      break;
74
75    // Don't desugar magic Objective-C types.
76    if (QualType(Ty,0) == Context.getObjCIdType() ||
77        QualType(Ty,0) == Context.getObjCClassType() ||
78        QualType(Ty,0) == Context.getObjCSelType() ||
79        QualType(Ty,0) == Context.getObjCProtoType())
80      break;
81
82    // Don't desugar va_list.
83    if (QualType(Ty,0) == Context.getBuiltinVaListType())
84      break;
85
86    // Otherwise, do a single-step desugar.
87    QualType Underlying;
88    bool IsSugar = false;
89    switch (Ty->getTypeClass()) {
90#define ABSTRACT_TYPE(Class, Base)
91#define TYPE(Class, Base) \
92    case Type::Class: { \
93      const Class##Type *CTy = cast<Class##Type>(Ty); \
94      if (CTy->isSugared()) { \
95        IsSugar = true; \
96        Underlying = CTy->desugar(); \
97      } \
98      break; \
99    }
100#include "clang/AST/TypeNodes.def"
101    }
102
103    // If it wasn't sugared, we're done.
104    if (!IsSugar)
105      break;
106
107    // If the desugared type is a vector type, we don't want to expand
108    // it, it will turn into an attribute mess. People want their "vec4".
109    if (isa<VectorType>(Underlying))
110      break;
111
112    // Otherwise, we're tearing through something opaque; note that
113    // we'll eventually need an a.k.a. clause and keep going.
114    AKA = true;
115    QT = Underlying;
116    continue;
117  }
118
119  // If we never tore through opaque sugar, don't print aka.
120  if (!AKA) return false;
121
122  // If we did, check to see if we already desugared this type in this
123  // diagnostic.  If so, don't do it again.
124  for (unsigned i = 0; i != NumPrevArgs; ++i) {
125    // TODO: Handle ak_declcontext case.
126    if (PrevArgs[i].first == Diagnostic::ak_qualtype) {
127      void *Ptr = (void*)PrevArgs[i].second;
128      QualType PrevTy(QualType::getFromOpaquePtr(Ptr));
129      if (PrevTy == InputTy)
130        return false;
131    }
132  }
133
134  DesugaredQT = Qc.apply(QT);
135  return true;
136}
137
138/// \brief Convert the given type to a string suitable for printing as part of
139/// a diagnostic.
140///
141/// \param Context the context in which the type was allocated
142/// \param Ty the type to print
143static std::string
144ConvertTypeToDiagnosticString(ASTContext &Context, QualType Ty,
145                              const Diagnostic::ArgumentValue *PrevArgs,
146                              unsigned NumPrevArgs) {
147  // FIXME: Playing with std::string is really slow.
148  std::string S = Ty.getAsString(Context.PrintingPolicy);
149
150  // Consider producing an a.k.a. clause if removing all the direct
151  // sugar gives us something "significantly different".
152
153  QualType DesugaredTy;
154  if (ShouldAKA(Context, Ty, PrevArgs, NumPrevArgs, DesugaredTy)) {
155    S = "'"+S+"' (aka '";
156    S += DesugaredTy.getAsString(Context.PrintingPolicy);
157    S += "')";
158    return S;
159  }
160
161  S = "'" + S + "'";
162  return S;
163}
164
165/// ConvertQualTypeToStringFn - This function is used to pretty print the
166/// specified QualType as a string in diagnostics.
167static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
168                                 const char *Modifier, unsigned ModLen,
169                                 const char *Argument, unsigned ArgLen,
170                                 const Diagnostic::ArgumentValue *PrevArgs,
171                                 unsigned NumPrevArgs,
172                                 llvm::SmallVectorImpl<char> &Output,
173                                 void *Cookie) {
174  ASTContext &Context = *static_cast<ASTContext*>(Cookie);
175
176  std::string S;
177  bool NeedQuotes = true;
178
179  switch (Kind) {
180  default: assert(0 && "unknown ArgumentKind");
181  case Diagnostic::ak_qualtype: {
182    assert(ModLen == 0 && ArgLen == 0 &&
183           "Invalid modifier for QualType argument");
184
185    QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
186    S = ConvertTypeToDiagnosticString(Context, Ty, PrevArgs, NumPrevArgs);
187    NeedQuotes = false;
188    break;
189  }
190  case Diagnostic::ak_declarationname: {
191    DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
192    S = N.getAsString();
193
194    if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
195      S = '+' + S;
196    else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
197      S = '-' + S;
198    else
199      assert(ModLen == 0 && ArgLen == 0 &&
200             "Invalid modifier for DeclarationName argument");
201    break;
202  }
203  case Diagnostic::ak_nameddecl: {
204    bool Qualified;
205    if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
206      Qualified = true;
207    else {
208      assert(ModLen == 0 && ArgLen == 0 &&
209           "Invalid modifier for NamedDecl* argument");
210      Qualified = false;
211    }
212    reinterpret_cast<NamedDecl*>(Val)->
213      getNameForDiagnostic(S, Context.PrintingPolicy, Qualified);
214    break;
215  }
216  case Diagnostic::ak_nestednamespec: {
217    llvm::raw_string_ostream OS(S);
218    reinterpret_cast<NestedNameSpecifier*>(Val)->print(OS,
219                                                       Context.PrintingPolicy);
220    NeedQuotes = false;
221    break;
222  }
223  case Diagnostic::ak_declcontext: {
224    DeclContext *DC = reinterpret_cast<DeclContext *> (Val);
225    assert(DC && "Should never have a null declaration context");
226
227    if (DC->isTranslationUnit()) {
228      // FIXME: Get these strings from some localized place
229      if (Context.getLangOptions().CPlusPlus)
230        S = "the global namespace";
231      else
232        S = "the global scope";
233    } else if (TypeDecl *Type = dyn_cast<TypeDecl>(DC)) {
234      S = ConvertTypeToDiagnosticString(Context, Context.getTypeDeclType(Type),
235                                        PrevArgs, NumPrevArgs);
236    } else {
237      // FIXME: Get these strings from some localized place
238      NamedDecl *ND = cast<NamedDecl>(DC);
239      if (isa<NamespaceDecl>(ND))
240        S += "namespace ";
241      else if (isa<ObjCMethodDecl>(ND))
242        S += "method ";
243      else if (isa<FunctionDecl>(ND))
244        S += "function ";
245
246      S += "'";
247      ND->getNameForDiagnostic(S, Context.PrintingPolicy, true);
248      S += "'";
249    }
250    NeedQuotes = false;
251    break;
252  }
253  }
254
255  if (NeedQuotes)
256    Output.push_back('\'');
257
258  Output.append(S.begin(), S.end());
259
260  if (NeedQuotes)
261    Output.push_back('\'');
262}
263
264
265static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
266  if (C.getLangOptions().CPlusPlus)
267    return CXXRecordDecl::Create(C, TagDecl::TK_struct,
268                                 C.getTranslationUnitDecl(),
269                                 SourceLocation(), &C.Idents.get(Name));
270
271  return RecordDecl::Create(C, TagDecl::TK_struct,
272                            C.getTranslationUnitDecl(),
273                            SourceLocation(), &C.Idents.get(Name));
274}
275
276void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
277  TUScope = S;
278  PushDeclContext(S, Context.getTranslationUnitDecl());
279
280  if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
281    DeclaratorInfo *DInfo;
282
283    // Install [u]int128_t for 64-bit targets.
284    DInfo = Context.getTrivialDeclaratorInfo(Context.Int128Ty);
285    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
286                                          SourceLocation(),
287                                          &Context.Idents.get("__int128_t"),
288                                          DInfo), TUScope);
289
290    DInfo = Context.getTrivialDeclaratorInfo(Context.UnsignedInt128Ty);
291    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
292                                          SourceLocation(),
293                                          &Context.Idents.get("__uint128_t"),
294                                          DInfo), TUScope);
295  }
296
297
298  if (!PP.getLangOptions().ObjC1) return;
299
300  // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
301  if (Context.getObjCSelType().isNull()) {
302    // Synthesize "typedef struct objc_selector *SEL;"
303    RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
304    PushOnScopeChains(SelTag, TUScope);
305
306    QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
307    DeclaratorInfo *SelInfo = Context.getTrivialDeclaratorInfo(SelT);
308    TypedefDecl *SelTypedef
309      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
310                            &Context.Idents.get("SEL"), SelInfo);
311    PushOnScopeChains(SelTypedef, TUScope);
312    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
313  }
314
315  // Synthesize "@class Protocol;
316  if (Context.getObjCProtoType().isNull()) {
317    ObjCInterfaceDecl *ProtocolDecl =
318      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
319                                &Context.Idents.get("Protocol"),
320                                SourceLocation(), true);
321    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
322    PushOnScopeChains(ProtocolDecl, TUScope);
323  }
324  // Create the built-in typedef for 'id'.
325  if (Context.getObjCIdType().isNull()) {
326    QualType IdT = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy);
327    DeclaratorInfo *IdInfo = Context.getTrivialDeclaratorInfo(IdT);
328    TypedefDecl *IdTypedef
329      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
330                            &Context.Idents.get("id"), IdInfo);
331    PushOnScopeChains(IdTypedef, TUScope);
332    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
333    Context.ObjCIdRedefinitionType = Context.getObjCIdType();
334  }
335  // Create the built-in typedef for 'Class'.
336  if (Context.getObjCClassType().isNull()) {
337    QualType ClassType
338      = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy);
339    DeclaratorInfo *ClassInfo = Context.getTrivialDeclaratorInfo(ClassType);
340    TypedefDecl *ClassTypedef
341      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
342                            &Context.Idents.get("Class"), ClassInfo);
343    PushOnScopeChains(ClassTypedef, TUScope);
344    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
345    Context.ObjCClassRedefinitionType = Context.getObjCClassType();
346  }
347}
348
349Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
350           bool CompleteTranslationUnit)
351  : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
352    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
353    ExternalSource(0), CodeCompleter(0), CurContext(0),
354    PreDeclaratorDC(0), CurBlock(0), PackContext(0), ParsingDeclDepth(0),
355    IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0),
356    GlobalNewDeleteDeclared(false), ExprEvalContext(PotentiallyEvaluated),
357    CompleteTranslationUnit(CompleteTranslationUnit),
358    NumSFINAEErrors(0), NonInstantiationEntries(0),
359    CurrentInstantiationScope(0)
360{
361  TUScope = 0;
362  if (getLangOptions().CPlusPlus)
363    FieldCollector.reset(new CXXFieldCollector());
364
365  // Tell diagnostics how to render things from the AST library.
366  PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
367}
368
369/// Retrieves the width and signedness of the given integer type,
370/// or returns false if it is not an integer type.
371///
372/// \param T must be canonical
373static bool getIntProperties(ASTContext &C, const Type *T,
374                             unsigned &BitWidth, bool &Signed) {
375  assert(T->isCanonicalUnqualified());
376
377  if (const VectorType *VT = dyn_cast<VectorType>(T))
378    T = VT->getElementType().getTypePtr();
379  if (const ComplexType *CT = dyn_cast<ComplexType>(T))
380    T = CT->getElementType().getTypePtr();
381
382  if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) {
383    if (!BT->isInteger()) return false;
384
385    BitWidth = C.getIntWidth(QualType(T, 0));
386    Signed = BT->isSignedInteger();
387    return true;
388  }
389
390  if (const FixedWidthIntType *FWIT = dyn_cast<FixedWidthIntType>(T)) {
391    BitWidth = FWIT->getWidth();
392    Signed = FWIT->isSigned();
393    return true;
394  }
395
396  return false;
397}
398
399/// Checks whether the given value will have the same value if it it
400/// is truncated to the given width, then extended back to the
401/// original width.
402static bool IsSameIntAfterCast(const llvm::APSInt &value,
403                               unsigned TargetWidth) {
404  unsigned SourceWidth = value.getBitWidth();
405  llvm::APSInt truncated = value;
406  truncated.trunc(TargetWidth);
407  truncated.extend(SourceWidth);
408  return (truncated == value);
409}
410
411/// Checks whether the given value will have the same value if it
412/// is truncated to the given width, then extended back to the original
413/// width.
414///
415/// The value might be a vector or a complex.
416static bool IsSameIntAfterCast(const APValue &value, unsigned TargetWidth) {
417  if (value.isInt())
418    return IsSameIntAfterCast(value.getInt(), TargetWidth);
419
420  if (value.isVector()) {
421    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
422      if (!IsSameIntAfterCast(value.getVectorElt(i), TargetWidth))
423        return false;
424    return true;
425  }
426
427  if (value.isComplexInt()) {
428    return IsSameIntAfterCast(value.getComplexIntReal(), TargetWidth) &&
429           IsSameIntAfterCast(value.getComplexIntImag(), TargetWidth);
430  }
431
432  // This can happen with lossless casts to intptr_t of "based" lvalues.
433  // Assume it might use arbitrary bits.
434  assert(value.isLValue());
435  return false;
436}
437
438
439/// Checks whether the given value, which currently has the given
440/// source semantics, has the same value when coerced through the
441/// target semantics.
442static bool IsSameFloatAfterCast(const llvm::APFloat &value,
443                                 const llvm::fltSemantics &Src,
444                                 const llvm::fltSemantics &Tgt) {
445  llvm::APFloat truncated = value;
446
447  bool ignored;
448  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
449  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
450
451  return truncated.bitwiseIsEqual(value);
452}
453
454/// Checks whether the given value, which currently has the given
455/// source semantics, has the same value when coerced through the
456/// target semantics.
457///
458/// The value might be a vector of floats (or a complex number).
459static bool IsSameFloatAfterCast(const APValue &value,
460                                 const llvm::fltSemantics &Src,
461                                 const llvm::fltSemantics &Tgt) {
462  if (value.isFloat())
463    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
464
465  if (value.isVector()) {
466    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
467      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
468        return false;
469    return true;
470  }
471
472  assert(value.isComplexFloat());
473  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
474          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
475}
476
477/// Determines if it's reasonable for the given expression to be truncated
478/// down to the given integer width.
479/// * Boolean expressions are automatically white-listed.
480/// * Arithmetic operations on implicitly-promoted operands of the
481///   target width or less are okay --- not because the results are
482///   actually guaranteed to fit within the width, but because the
483///   user is effectively pretending that the operations are closed
484///   within the implicitly-promoted type.
485static bool IsExprValueWithinWidth(ASTContext &C, Expr *E, unsigned Width) {
486  E = E->IgnoreParens();
487
488#ifndef NDEBUG
489  {
490    const Type *ETy = E->getType()->getCanonicalTypeInternal().getTypePtr();
491    unsigned EWidth;
492    bool ESigned;
493
494    if (!getIntProperties(C, ETy, EWidth, ESigned))
495      assert(0 && "expression not of integer type");
496
497    // The caller should never let this happen.
498    assert(EWidth > Width && "called on expr whose type is too small");
499  }
500#endif
501
502  // Strip implicit casts off.
503  while (isa<ImplicitCastExpr>(E)) {
504    E = cast<ImplicitCastExpr>(E)->getSubExpr();
505
506    const Type *ETy = E->getType()->getCanonicalTypeInternal().getTypePtr();
507
508    unsigned EWidth;
509    bool ESigned;
510    if (!getIntProperties(C, ETy, EWidth, ESigned))
511      return false;
512
513    if (EWidth <= Width)
514      return true;
515  }
516
517  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
518    switch (BO->getOpcode()) {
519
520    // Boolean-valued operations are white-listed.
521    case BinaryOperator::LAnd:
522    case BinaryOperator::LOr:
523    case BinaryOperator::LT:
524    case BinaryOperator::GT:
525    case BinaryOperator::LE:
526    case BinaryOperator::GE:
527    case BinaryOperator::EQ:
528    case BinaryOperator::NE:
529      return true;
530
531    // Operations with opaque sources are black-listed.
532    case BinaryOperator::PtrMemD:
533    case BinaryOperator::PtrMemI:
534      return false;
535
536    // Left shift gets black-listed based on a judgement call.
537    case BinaryOperator::Shl:
538      return false;
539
540    // Various special cases.
541    case BinaryOperator::Shr:
542      return IsExprValueWithinWidth(C, BO->getLHS(), Width);
543    case BinaryOperator::Comma:
544      return IsExprValueWithinWidth(C, BO->getRHS(), Width);
545    case BinaryOperator::Sub:
546      if (BO->getLHS()->getType()->isPointerType())
547        return false;
548      // fallthrough
549
550    // Any other operator is okay if the operands are
551    // promoted from expressions of appropriate size.
552    default:
553      return IsExprValueWithinWidth(C, BO->getLHS(), Width) &&
554             IsExprValueWithinWidth(C, BO->getRHS(), Width);
555    }
556  }
557
558  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
559    switch (UO->getOpcode()) {
560    // Boolean-valued operations are white-listed.
561    case UnaryOperator::LNot:
562      return true;
563
564    // Operations with opaque sources are black-listed.
565    case UnaryOperator::Deref:
566    case UnaryOperator::AddrOf: // should be impossible
567      return false;
568
569    case UnaryOperator::OffsetOf:
570      return false;
571
572    default:
573      return IsExprValueWithinWidth(C, UO->getSubExpr(), Width);
574    }
575  }
576
577  // Don't diagnose if the expression is an integer constant
578  // whose value in the target type is the same as it was
579  // in the original type.
580  Expr::EvalResult result;
581  if (E->Evaluate(result, C))
582    if (IsSameIntAfterCast(result.Val, Width))
583      return true;
584
585  return false;
586}
587
588/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
589static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
590  S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
591}
592
593/// Implements -Wconversion.
594static void CheckImplicitConversion(Sema &S, Expr *E, QualType T) {
595  // Don't diagnose in unevaluated contexts.
596  if (S.ExprEvalContext == Sema::Unevaluated)
597    return;
598
599  // Don't diagnose for value-dependent expressions.
600  if (E->isValueDependent())
601    return;
602
603  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
604  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
605
606  // Never diagnose implicit casts to bool.
607  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
608    return;
609
610  // Strip vector types.
611  if (isa<VectorType>(Source)) {
612    if (!isa<VectorType>(Target))
613      return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar);
614
615    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
616    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
617  }
618
619  // Strip complex types.
620  if (isa<ComplexType>(Source)) {
621    if (!isa<ComplexType>(Target))
622      return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar);
623
624    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
625    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
626  }
627
628  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
629  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
630
631  // If the source is floating point...
632  if (SourceBT && SourceBT->isFloatingPoint()) {
633    // ...and the target is floating point...
634    if (TargetBT && TargetBT->isFloatingPoint()) {
635      // ...then warn if we're dropping FP rank.
636
637      // Builtin FP kinds are ordered by increasing FP rank.
638      if (SourceBT->getKind() > TargetBT->getKind()) {
639        // Don't warn about float constants that are precisely
640        // representable in the target type.
641        Expr::EvalResult result;
642        if (E->Evaluate(result, S.Context)) {
643          // Value might be a float, a float vector, or a float complex.
644          if (IsSameFloatAfterCast(result.Val,
645                     S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
646                     S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
647            return;
648        }
649
650        DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision);
651      }
652      return;
653    }
654
655    // If the target is integral, always warn.
656    if ((TargetBT && TargetBT->isInteger()) ||
657        isa<FixedWidthIntType>(Target))
658      // TODO: don't warn for integer values?
659      return DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer);
660
661    return;
662  }
663
664  unsigned SourceWidth, TargetWidth;
665  bool SourceSigned, TargetSigned;
666
667  if (!getIntProperties(S.Context, Source, SourceWidth, SourceSigned) ||
668      !getIntProperties(S.Context, Target, TargetWidth, TargetSigned))
669    return;
670
671  if (SourceWidth > TargetWidth) {
672    if (IsExprValueWithinWidth(S.Context, E, TargetWidth))
673      return;
674
675    // People want to build with -Wshorten-64-to-32 and not -Wconversion
676    // and by god we'll let them.
677    if (SourceWidth == 64 && TargetWidth == 32)
678      return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32);
679    return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision);
680  }
681
682  return;
683}
684
685/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
686/// If there is already an implicit cast, merge into the existing one.
687/// If isLvalue, the result of the cast is an lvalue.
688void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
689                             CastExpr::CastKind Kind, bool isLvalue) {
690  QualType ExprTy = Context.getCanonicalType(Expr->getType());
691  QualType TypeTy = Context.getCanonicalType(Ty);
692
693  if (ExprTy == TypeTy)
694    return;
695
696  if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
697    QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
698    QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
699    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
700      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
701        << Expr->getSourceRange();
702    }
703  }
704
705  CheckImplicitConversion(*this, Expr, Ty);
706
707  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
708    if (ImpCast->getCastKind() == Kind) {
709      ImpCast->setType(Ty);
710      ImpCast->setLvalueCast(isLvalue);
711      return;
712    }
713  }
714
715  Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue);
716}
717
718void Sema::DeleteExpr(ExprTy *E) {
719  if (E) static_cast<Expr*>(E)->Destroy(Context);
720}
721void Sema::DeleteStmt(StmtTy *S) {
722  if (S) static_cast<Stmt*>(S)->Destroy(Context);
723}
724
725/// ActOnEndOfTranslationUnit - This is called at the very end of the
726/// translation unit when EOF is reached and all but the top-level scope is
727/// popped.
728void Sema::ActOnEndOfTranslationUnit() {
729  // C++: Perform implicit template instantiations.
730  //
731  // FIXME: When we perform these implicit instantiations, we do not carefully
732  // keep track of the point of instantiation (C++ [temp.point]). This means
733  // that name lookup that occurs within the template instantiation will
734  // always happen at the end of the translation unit, so it will find
735  // some names that should not be found. Although this is common behavior
736  // for C++ compilers, it is technically wrong. In the future, we either need
737  // to be able to filter the results of name lookup or we need to perform
738  // template instantiations earlier.
739  PerformPendingImplicitInstantiations();
740
741  // Check for #pragma weak identifiers that were never declared
742  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
743  // order!  Iterating over a densemap like this is bad.
744  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
745       I = WeakUndeclaredIdentifiers.begin(),
746       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
747    if (I->second.getUsed()) continue;
748
749    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
750      << I->first;
751  }
752
753  if (!CompleteTranslationUnit)
754    return;
755
756  // C99 6.9.2p2:
757  //   A declaration of an identifier for an object that has file
758  //   scope without an initializer, and without a storage-class
759  //   specifier or with the storage-class specifier static,
760  //   constitutes a tentative definition. If a translation unit
761  //   contains one or more tentative definitions for an identifier,
762  //   and the translation unit contains no external definition for
763  //   that identifier, then the behavior is exactly as if the
764  //   translation unit contains a file scope declaration of that
765  //   identifier, with the composite type as of the end of the
766  //   translation unit, with an initializer equal to 0.
767  for (unsigned i = 0, e = TentativeDefinitionList.size(); i != e; ++i) {
768    VarDecl *VD = TentativeDefinitions.lookup(TentativeDefinitionList[i]);
769
770    // If the tentative definition was completed, it will be in the list, but
771    // not the map.
772    if (VD == 0 || VD->isInvalidDecl() || !VD->isTentativeDefinition(Context))
773      continue;
774
775    if (const IncompleteArrayType *ArrayT
776        = Context.getAsIncompleteArrayType(VD->getType())) {
777      if (RequireCompleteType(VD->getLocation(),
778                              ArrayT->getElementType(),
779                              diag::err_tentative_def_incomplete_type_arr)) {
780        VD->setInvalidDecl();
781        continue;
782      }
783
784      // Set the length of the array to 1 (C99 6.9.2p5).
785      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
786      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
787      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
788                                                One, ArrayType::Normal, 0);
789      VD->setType(T);
790    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
791                                   diag::err_tentative_def_incomplete_type))
792      VD->setInvalidDecl();
793
794    // Notify the consumer that we've completed a tentative definition.
795    if (!VD->isInvalidDecl())
796      Consumer.CompleteTentativeDefinition(VD);
797
798  }
799}
800
801
802//===----------------------------------------------------------------------===//
803// Helper functions.
804//===----------------------------------------------------------------------===//
805
806DeclContext *Sema::getFunctionLevelDeclContext() {
807  DeclContext *DC = PreDeclaratorDC ? PreDeclaratorDC : CurContext;
808
809  while (isa<BlockDecl>(DC))
810    DC = DC->getParent();
811
812  return DC;
813}
814
815/// getCurFunctionDecl - If inside of a function body, this returns a pointer
816/// to the function decl for the function being parsed.  If we're currently
817/// in a 'block', this returns the containing context.
818FunctionDecl *Sema::getCurFunctionDecl() {
819  DeclContext *DC = getFunctionLevelDeclContext();
820  return dyn_cast<FunctionDecl>(DC);
821}
822
823ObjCMethodDecl *Sema::getCurMethodDecl() {
824  DeclContext *DC = getFunctionLevelDeclContext();
825  return dyn_cast<ObjCMethodDecl>(DC);
826}
827
828NamedDecl *Sema::getCurFunctionOrMethodDecl() {
829  DeclContext *DC = getFunctionLevelDeclContext();
830  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
831    return cast<NamedDecl>(DC);
832  return 0;
833}
834
835Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
836  if (!this->Emit())
837    return;
838
839  // If this is not a note, and we're in a template instantiation
840  // that is different from the last template instantiation where
841  // we emitted an error, print a template instantiation
842  // backtrace.
843  if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
844      !SemaRef.ActiveTemplateInstantiations.empty() &&
845      SemaRef.ActiveTemplateInstantiations.back()
846        != SemaRef.LastTemplateInstantiationErrorContext) {
847    SemaRef.PrintInstantiationStack();
848    SemaRef.LastTemplateInstantiationErrorContext
849      = SemaRef.ActiveTemplateInstantiations.back();
850  }
851}
852
853Sema::SemaDiagnosticBuilder
854Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
855  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
856  PD.Emit(Builder);
857
858  return Builder;
859}
860
861void Sema::ActOnComment(SourceRange Comment) {
862  Context.Comments.push_back(Comment);
863}
864
865