Home | History | Annotate | Download | only in CodeGen
      1 //===--- CGDeclCXX.cpp - Emit LLVM Code for C++ declarations --------------===//
      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 contains code dealing with code generation of C++ declarations
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "CodeGenFunction.h"
     15 #include "CGCXXABI.h"
     16 #include "CGObjCRuntime.h"
     17 #include "clang/Frontend/CodeGenOptions.h"
     18 #include "llvm/ADT/StringExtras.h"
     19 #include "llvm/IR/Intrinsics.h"
     20 
     21 using namespace clang;
     22 using namespace CodeGen;
     23 
     24 static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
     25                          llvm::Constant *DeclPtr) {
     26   assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
     27   assert(!D.getType()->isReferenceType() &&
     28          "Should not call EmitDeclInit on a reference!");
     29 
     30   ASTContext &Context = CGF.getContext();
     31 
     32   CharUnits alignment = Context.getDeclAlign(&D);
     33   QualType type = D.getType();
     34   LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
     35 
     36   const Expr *Init = D.getInit();
     37   switch (CGF.getEvaluationKind(type)) {
     38   case TEK_Scalar: {
     39     CodeGenModule &CGM = CGF.CGM;
     40     if (lv.isObjCStrong())
     41       CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
     42                                                 DeclPtr, D.isThreadSpecified());
     43     else if (lv.isObjCWeak())
     44       CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
     45                                               DeclPtr);
     46     else
     47       CGF.EmitScalarInit(Init, &D, lv, false);
     48     return;
     49   }
     50   case TEK_Complex:
     51     CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
     52     return;
     53   case TEK_Aggregate:
     54     CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
     55                                           AggValueSlot::DoesNotNeedGCBarriers,
     56                                                   AggValueSlot::IsNotAliased));
     57     return;
     58   }
     59   llvm_unreachable("bad evaluation kind");
     60 }
     61 
     62 /// Emit code to cause the destruction of the given variable with
     63 /// static storage duration.
     64 static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
     65                             llvm::Constant *addr) {
     66   CodeGenModule &CGM = CGF.CGM;
     67 
     68   // FIXME:  __attribute__((cleanup)) ?
     69 
     70   QualType type = D.getType();
     71   QualType::DestructionKind dtorKind = type.isDestructedType();
     72 
     73   switch (dtorKind) {
     74   case QualType::DK_none:
     75     return;
     76 
     77   case QualType::DK_cxx_destructor:
     78     break;
     79 
     80   case QualType::DK_objc_strong_lifetime:
     81   case QualType::DK_objc_weak_lifetime:
     82     // We don't care about releasing objects during process teardown.
     83     return;
     84   }
     85 
     86   llvm::Constant *function;
     87   llvm::Constant *argument;
     88 
     89   // Special-case non-array C++ destructors, where there's a function
     90   // with the right signature that we can just call.
     91   const CXXRecordDecl *record = 0;
     92   if (dtorKind == QualType::DK_cxx_destructor &&
     93       (record = type->getAsCXXRecordDecl())) {
     94     assert(!record->hasTrivialDestructor());
     95     CXXDestructorDecl *dtor = record->getDestructor();
     96 
     97     function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
     98     argument = addr;
     99 
    100   // Otherwise, the standard logic requires a helper function.
    101   } else {
    102     function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
    103                                                   CGF.getDestroyer(dtorKind),
    104                                                   CGF.needsEHCleanup(dtorKind));
    105     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
    106   }
    107 
    108   CGM.getCXXABI().registerGlobalDtor(CGF, function, argument);
    109 }
    110 
    111 /// Emit code to cause the variable at the given address to be considered as
    112 /// constant from this point onwards.
    113 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
    114                               llvm::Constant *Addr) {
    115   // Don't emit the intrinsic if we're not optimizing.
    116   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
    117     return;
    118 
    119   // Grab the llvm.invariant.start intrinsic.
    120   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
    121   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
    122 
    123   // Emit a call with the size in bytes of the object.
    124   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
    125   uint64_t Width = WidthChars.getQuantity();
    126   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
    127                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
    128   CGF.Builder.CreateCall(InvariantStart, Args);
    129 }
    130 
    131 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
    132                                                llvm::Constant *DeclPtr,
    133                                                bool PerformInit) {
    134 
    135   const Expr *Init = D.getInit();
    136   QualType T = D.getType();
    137 
    138   if (!T->isReferenceType()) {
    139     if (PerformInit)
    140       EmitDeclInit(*this, D, DeclPtr);
    141     if (CGM.isTypeConstant(D.getType(), true))
    142       EmitDeclInvariant(*this, D, DeclPtr);
    143     else
    144       EmitDeclDestroy(*this, D, DeclPtr);
    145     return;
    146   }
    147 
    148   assert(PerformInit && "cannot have constant initializer which needs "
    149          "destruction for reference");
    150   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
    151   RValue RV = EmitReferenceBindingToExpr(Init, &D);
    152   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
    153 }
    154 
    155 static llvm::Function *
    156 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
    157                                    llvm::FunctionType *ty,
    158                                    const Twine &name);
    159 
    160 /// Create a stub function, suitable for being passed to atexit,
    161 /// which passes the given address to the given destructor function.
    162 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
    163                                         llvm::Constant *dtor,
    164                                         llvm::Constant *addr) {
    165   // Get the destructor function type, void(*)(void).
    166   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
    167   llvm::Function *fn =
    168     CreateGlobalInitOrDestructFunction(CGM, ty,
    169                                        Twine("__dtor_", addr->getName()));
    170 
    171   CodeGenFunction CGF(CGM);
    172 
    173   // Initialize debug info if needed.
    174   CGF.maybeInitializeDebugInfo();
    175 
    176   CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
    177                     CGM.getTypes().arrangeNullaryFunction(),
    178                     FunctionArgList(), SourceLocation());
    179 
    180   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
    181 
    182  // Make sure the call and the callee agree on calling convention.
    183   if (llvm::Function *dtorFn =
    184         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
    185     call->setCallingConv(dtorFn->getCallingConv());
    186 
    187   CGF.FinishFunction();
    188 
    189   return fn;
    190 }
    191 
    192 /// Register a global destructor using the C atexit runtime function.
    193 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtor,
    194                                                    llvm::Constant *addr) {
    195   // Create a function which calls the destructor.
    196   llvm::Constant *dtorStub = createAtExitStub(CGM, dtor, addr);
    197 
    198   // extern "C" int atexit(void (*f)(void));
    199   llvm::FunctionType *atexitTy =
    200     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
    201 
    202   llvm::Constant *atexit =
    203     CGM.CreateRuntimeFunction(atexitTy, "atexit");
    204   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
    205     atexitFn->setDoesNotThrow();
    206 
    207   EmitNounwindRuntimeCall(atexit, dtorStub);
    208 }
    209 
    210 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
    211                                          llvm::GlobalVariable *DeclPtr,
    212                                          bool PerformInit) {
    213   // If we've been asked to forbid guard variables, emit an error now.
    214   // This diagnostic is hard-coded for Darwin's use case;  we can find
    215   // better phrasing if someone else needs it.
    216   if (CGM.getCodeGenOpts().ForbidGuardVariables)
    217     CGM.Error(D.getLocation(),
    218               "this initialization requires a guard variable, which "
    219               "the kernel does not support");
    220 
    221   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
    222 }
    223 
    224 static llvm::Function *
    225 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
    226                                    llvm::FunctionType *FTy,
    227                                    const Twine &Name) {
    228   llvm::Function *Fn =
    229     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
    230                            Name, &CGM.getModule());
    231   if (!CGM.getLangOpts().AppleKext) {
    232     // Set the section if needed.
    233     if (const char *Section =
    234           CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
    235       Fn->setSection(Section);
    236   }
    237 
    238   Fn->setCallingConv(CGM.getRuntimeCC());
    239 
    240   if (!CGM.getLangOpts().Exceptions)
    241     Fn->setDoesNotThrow();
    242 
    243   if (CGM.getSanOpts().Address)
    244     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
    245   if (CGM.getSanOpts().Thread)
    246     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
    247   if (CGM.getSanOpts().Memory)
    248     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
    249 
    250   return Fn;
    251 }
    252 
    253 void
    254 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
    255                                             llvm::GlobalVariable *Addr,
    256                                             bool PerformInit) {
    257   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    258 
    259   // Create a variable initialization function.
    260   llvm::Function *Fn =
    261     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
    262 
    263   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
    264                                                           PerformInit);
    265 
    266   if (D->hasAttr<InitPriorityAttr>()) {
    267     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
    268     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
    269     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
    270     DelayedCXXInitPosition.erase(D);
    271   }  else {
    272     llvm::DenseMap<const Decl *, unsigned>::iterator I =
    273       DelayedCXXInitPosition.find(D);
    274     if (I == DelayedCXXInitPosition.end()) {
    275       CXXGlobalInits.push_back(Fn);
    276     } else {
    277       assert(CXXGlobalInits[I->second] == 0);
    278       CXXGlobalInits[I->second] = Fn;
    279       DelayedCXXInitPosition.erase(I);
    280     }
    281   }
    282 }
    283 
    284 void
    285 CodeGenModule::EmitCXXGlobalInitFunc() {
    286   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
    287     CXXGlobalInits.pop_back();
    288 
    289   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
    290     return;
    291 
    292   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    293 
    294 
    295   // Create our global initialization function.
    296   if (!PrioritizedCXXGlobalInits.empty()) {
    297     SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
    298     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
    299                          PrioritizedCXXGlobalInits.end());
    300     // Iterate over "chunks" of ctors with same priority and emit each chunk
    301     // into separate function. Note - everything is sorted first by priority,
    302     // second - by lex order, so we emit ctor functions in proper order.
    303     for (SmallVectorImpl<GlobalInitData >::iterator
    304            I = PrioritizedCXXGlobalInits.begin(),
    305            E = PrioritizedCXXGlobalInits.end(); I != E; ) {
    306       SmallVectorImpl<GlobalInitData >::iterator
    307         PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
    308 
    309       LocalCXXGlobalInits.clear();
    310       unsigned Priority = I->first.priority;
    311       // Compute the function suffix from priority. Prepend with zeroes to make
    312       // sure the function names are also ordered as priorities.
    313       std::string PrioritySuffix = llvm::utostr(Priority);
    314       // Priority is always <= 65535 (enforced by sema)..
    315       PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
    316       llvm::Function *Fn =
    317         CreateGlobalInitOrDestructFunction(*this, FTy,
    318                                            "_GLOBAL__I_" + PrioritySuffix);
    319 
    320       for (; I < PrioE; ++I)
    321         LocalCXXGlobalInits.push_back(I->second);
    322 
    323       CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
    324                                                     &LocalCXXGlobalInits[0],
    325                                                     LocalCXXGlobalInits.size());
    326       AddGlobalCtor(Fn, Priority);
    327     }
    328   }
    329 
    330   llvm::Function *Fn =
    331     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
    332 
    333   CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
    334                                                    &CXXGlobalInits[0],
    335                                                    CXXGlobalInits.size());
    336   AddGlobalCtor(Fn);
    337 
    338   CXXGlobalInits.clear();
    339   PrioritizedCXXGlobalInits.clear();
    340 }
    341 
    342 void CodeGenModule::EmitCXXGlobalDtorFunc() {
    343   if (CXXGlobalDtors.empty())
    344     return;
    345 
    346   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    347 
    348   // Create our global destructor function.
    349   llvm::Function *Fn =
    350     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
    351 
    352   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
    353   AddGlobalDtor(Fn);
    354 }
    355 
    356 /// Emit the code necessary to initialize the given global variable.
    357 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
    358                                                        const VarDecl *D,
    359                                                  llvm::GlobalVariable *Addr,
    360                                                        bool PerformInit) {
    361   // Check if we need to emit debug info for variable initializer.
    362   if (!D->hasAttr<NoDebugAttr>())
    363     maybeInitializeDebugInfo();
    364 
    365   StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
    366                 getTypes().arrangeNullaryFunction(),
    367                 FunctionArgList(), D->getInit()->getExprLoc());
    368 
    369   // Use guarded initialization if the global variable is weak. This
    370   // occurs for, e.g., instantiated static data members and
    371   // definitions explicitly marked weak.
    372   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
    373       Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
    374     EmitCXXGuardedInit(*D, Addr, PerformInit);
    375   } else {
    376     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
    377   }
    378 
    379   FinishFunction();
    380 }
    381 
    382 void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
    383                                                 llvm::Constant **Decls,
    384                                                 unsigned NumDecls) {
    385   // Initialize debug info if needed.
    386   maybeInitializeDebugInfo();
    387 
    388   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
    389                 getTypes().arrangeNullaryFunction(),
    390                 FunctionArgList(), SourceLocation());
    391 
    392   RunCleanupsScope Scope(*this);
    393 
    394   // When building in Objective-C++ ARC mode, create an autorelease pool
    395   // around the global initializers.
    396   if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
    397     llvm::Value *token = EmitObjCAutoreleasePoolPush();
    398     EmitObjCAutoreleasePoolCleanup(token);
    399   }
    400 
    401   for (unsigned i = 0; i != NumDecls; ++i)
    402     if (Decls[i])
    403       EmitRuntimeCall(Decls[i]);
    404 
    405   Scope.ForceCleanup();
    406 
    407   FinishFunction();
    408 }
    409 
    410 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
    411                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
    412                                                 &DtorsAndObjects) {
    413   // Initialize debug info if needed.
    414   maybeInitializeDebugInfo();
    415 
    416   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
    417                 getTypes().arrangeNullaryFunction(),
    418                 FunctionArgList(), SourceLocation());
    419 
    420   // Emit the dtors, in reverse order from construction.
    421   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
    422     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
    423     llvm::CallInst *CI = Builder.CreateCall(Callee,
    424                                             DtorsAndObjects[e - i - 1].second);
    425     // Make sure the call and the callee agree on calling convention.
    426     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
    427       CI->setCallingConv(F->getCallingConv());
    428   }
    429 
    430   FinishFunction();
    431 }
    432 
    433 /// generateDestroyHelper - Generates a helper function which, when
    434 /// invoked, destroys the given object.
    435 llvm::Function *
    436 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
    437                                        QualType type,
    438                                        Destroyer *destroyer,
    439                                        bool useEHCleanupForArray) {
    440   FunctionArgList args;
    441   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
    442   args.push_back(&dst);
    443 
    444   const CGFunctionInfo &FI =
    445     CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
    446                                               FunctionType::ExtInfo(),
    447                                               /*variadic*/ false);
    448   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
    449   llvm::Function *fn =
    450     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
    451 
    452   // Initialize debug info if needed.
    453   maybeInitializeDebugInfo();
    454 
    455   StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
    456                 SourceLocation());
    457 
    458   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
    459 
    460   FinishFunction();
    461 
    462   return fn;
    463 }
    464