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.getTLSKind());
     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     assert(!D.getTLSKind() && "should have rejected this");
     84     return;
     85   }
     86 
     87   llvm::Constant *function;
     88   llvm::Constant *argument;
     89 
     90   // Special-case non-array C++ destructors, where there's a function
     91   // with the right signature that we can just call.
     92   const CXXRecordDecl *record = 0;
     93   if (dtorKind == QualType::DK_cxx_destructor &&
     94       (record = type->getAsCXXRecordDecl())) {
     95     assert(!record->hasTrivialDestructor());
     96     CXXDestructorDecl *dtor = record->getDestructor();
     97 
     98     function = CGM.GetAddrOfCXXDestructor(dtor, Dtor_Complete);
     99     argument = addr;
    100 
    101   // Otherwise, the standard logic requires a helper function.
    102   } else {
    103     function = CodeGenFunction(CGM).generateDestroyHelper(addr, type,
    104                                                   CGF.getDestroyer(dtorKind),
    105                                                   CGF.needsEHCleanup(dtorKind));
    106     argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
    107   }
    108 
    109   CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
    110 }
    111 
    112 /// Emit code to cause the variable at the given address to be considered as
    113 /// constant from this point onwards.
    114 static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
    115                               llvm::Constant *Addr) {
    116   // Don't emit the intrinsic if we're not optimizing.
    117   if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
    118     return;
    119 
    120   // Grab the llvm.invariant.start intrinsic.
    121   llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
    122   llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
    123 
    124   // Emit a call with the size in bytes of the object.
    125   CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
    126   uint64_t Width = WidthChars.getQuantity();
    127   llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
    128                            llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
    129   CGF.Builder.CreateCall(InvariantStart, Args);
    130 }
    131 
    132 void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
    133                                                llvm::Constant *DeclPtr,
    134                                                bool PerformInit) {
    135 
    136   const Expr *Init = D.getInit();
    137   QualType T = D.getType();
    138 
    139   if (!T->isReferenceType()) {
    140     if (PerformInit)
    141       EmitDeclInit(*this, D, DeclPtr);
    142     if (CGM.isTypeConstant(D.getType(), true))
    143       EmitDeclInvariant(*this, D, DeclPtr);
    144     else
    145       EmitDeclDestroy(*this, D, DeclPtr);
    146     return;
    147   }
    148 
    149   assert(PerformInit && "cannot have constant initializer which needs "
    150          "destruction for reference");
    151   unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
    152   RValue RV = EmitReferenceBindingToExpr(Init);
    153   EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
    154 }
    155 
    156 static llvm::Function *
    157 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
    158                                    llvm::FunctionType *ty,
    159                                    const Twine &name,
    160                                    bool TLS = false);
    161 
    162 /// Create a stub function, suitable for being passed to atexit,
    163 /// which passes the given address to the given destructor function.
    164 static llvm::Constant *createAtExitStub(CodeGenModule &CGM,
    165                                         llvm::Constant *dtor,
    166                                         llvm::Constant *addr) {
    167   // Get the destructor function type, void(*)(void).
    168   llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
    169   llvm::Function *fn =
    170     CreateGlobalInitOrDestructFunction(CGM, ty,
    171                                        Twine("__dtor_", addr->getName()));
    172 
    173   CodeGenFunction CGF(CGM);
    174 
    175   // Initialize debug info if needed.
    176   CGF.maybeInitializeDebugInfo();
    177 
    178   CGF.StartFunction(GlobalDecl(), CGM.getContext().VoidTy, fn,
    179                     CGM.getTypes().arrangeNullaryFunction(),
    180                     FunctionArgList(), SourceLocation());
    181 
    182   llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
    183 
    184  // Make sure the call and the callee agree on calling convention.
    185   if (llvm::Function *dtorFn =
    186         dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
    187     call->setCallingConv(dtorFn->getCallingConv());
    188 
    189   CGF.FinishFunction();
    190 
    191   return fn;
    192 }
    193 
    194 /// Register a global destructor using the C atexit runtime function.
    195 void CodeGenFunction::registerGlobalDtorWithAtExit(llvm::Constant *dtor,
    196                                                    llvm::Constant *addr) {
    197   // Create a function which calls the destructor.
    198   llvm::Constant *dtorStub = createAtExitStub(CGM, dtor, addr);
    199 
    200   // extern "C" int atexit(void (*f)(void));
    201   llvm::FunctionType *atexitTy =
    202     llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
    203 
    204   llvm::Constant *atexit =
    205     CGM.CreateRuntimeFunction(atexitTy, "atexit");
    206   if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
    207     atexitFn->setDoesNotThrow();
    208 
    209   EmitNounwindRuntimeCall(atexit, dtorStub);
    210 }
    211 
    212 void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
    213                                          llvm::GlobalVariable *DeclPtr,
    214                                          bool PerformInit) {
    215   // If we've been asked to forbid guard variables, emit an error now.
    216   // This diagnostic is hard-coded for Darwin's use case;  we can find
    217   // better phrasing if someone else needs it.
    218   if (CGM.getCodeGenOpts().ForbidGuardVariables)
    219     CGM.Error(D.getLocation(),
    220               "this initialization requires a guard variable, which "
    221               "the kernel does not support");
    222 
    223   CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
    224 }
    225 
    226 static llvm::Function *
    227 CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
    228                                    llvm::FunctionType *FTy,
    229                                    const Twine &Name, bool TLS) {
    230   llvm::Function *Fn =
    231     llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
    232                            Name, &CGM.getModule());
    233   if (!CGM.getLangOpts().AppleKext && !TLS) {
    234     // Set the section if needed.
    235     if (const char *Section =
    236           CGM.getTarget().getStaticInitSectionSpecifier())
    237       Fn->setSection(Section);
    238   }
    239 
    240   Fn->setCallingConv(CGM.getRuntimeCC());
    241 
    242   if (!CGM.getLangOpts().Exceptions)
    243     Fn->setDoesNotThrow();
    244 
    245   if (CGM.getSanOpts().Address)
    246     Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
    247   if (CGM.getSanOpts().Thread)
    248     Fn->addFnAttr(llvm::Attribute::SanitizeThread);
    249   if (CGM.getSanOpts().Memory)
    250     Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
    251 
    252   return Fn;
    253 }
    254 
    255 void
    256 CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
    257                                             llvm::GlobalVariable *Addr,
    258                                             bool PerformInit) {
    259   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    260 
    261   // Create a variable initialization function.
    262   llvm::Function *Fn =
    263     CreateGlobalInitOrDestructFunction(*this, FTy, "__cxx_global_var_init");
    264 
    265   CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
    266                                                           PerformInit);
    267 
    268   if (D->getTLSKind()) {
    269     // FIXME: Should we support init_priority for thread_local?
    270     // FIXME: Ideally, initialization of instantiated thread_local static data
    271     // members of class templates should not trigger initialization of other
    272     // entities in the TU.
    273     // FIXME: We only need to register one __cxa_thread_atexit function for the
    274     // entire TU.
    275     CXXThreadLocalInits.push_back(Fn);
    276   } else if (D->hasAttr<InitPriorityAttr>()) {
    277     unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
    278     OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
    279     PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
    280     DelayedCXXInitPosition.erase(D);
    281   } else {
    282     llvm::DenseMap<const Decl *, unsigned>::iterator I =
    283       DelayedCXXInitPosition.find(D);
    284     if (I == DelayedCXXInitPosition.end()) {
    285       CXXGlobalInits.push_back(Fn);
    286     } else {
    287       assert(CXXGlobalInits[I->second] == 0);
    288       CXXGlobalInits[I->second] = Fn;
    289       DelayedCXXInitPosition.erase(I);
    290     }
    291   }
    292 }
    293 
    294 void CodeGenModule::EmitCXXThreadLocalInitFunc() {
    295   llvm::Function *InitFn = 0;
    296   if (!CXXThreadLocalInits.empty()) {
    297     // Generate a guarded initialization function.
    298     llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    299     InitFn = CreateGlobalInitOrDestructFunction(*this, FTy, "__tls_init",
    300                                                 /*TLS*/ true);
    301     llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
    302         getModule(), Int8Ty, false, llvm::GlobalVariable::InternalLinkage,
    303         llvm::ConstantInt::get(Int8Ty, 0), "__tls_guard");
    304     Guard->setThreadLocal(true);
    305     CodeGenFunction(*this)
    306         .GenerateCXXGlobalInitFunc(InitFn, CXXThreadLocalInits, Guard);
    307   }
    308 
    309   getCXXABI().EmitThreadLocalInitFuncs(CXXThreadLocals, InitFn);
    310 
    311   CXXThreadLocalInits.clear();
    312   CXXThreadLocals.clear();
    313 }
    314 
    315 void
    316 CodeGenModule::EmitCXXGlobalInitFunc() {
    317   while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
    318     CXXGlobalInits.pop_back();
    319 
    320   if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
    321     return;
    322 
    323   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    324 
    325 
    326   // Create our global initialization function.
    327   if (!PrioritizedCXXGlobalInits.empty()) {
    328     SmallVector<llvm::Constant*, 8> LocalCXXGlobalInits;
    329     llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
    330                          PrioritizedCXXGlobalInits.end());
    331     // Iterate over "chunks" of ctors with same priority and emit each chunk
    332     // into separate function. Note - everything is sorted first by priority,
    333     // second - by lex order, so we emit ctor functions in proper order.
    334     for (SmallVectorImpl<GlobalInitData >::iterator
    335            I = PrioritizedCXXGlobalInits.begin(),
    336            E = PrioritizedCXXGlobalInits.end(); I != E; ) {
    337       SmallVectorImpl<GlobalInitData >::iterator
    338         PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
    339 
    340       LocalCXXGlobalInits.clear();
    341       unsigned Priority = I->first.priority;
    342       // Compute the function suffix from priority. Prepend with zeroes to make
    343       // sure the function names are also ordered as priorities.
    344       std::string PrioritySuffix = llvm::utostr(Priority);
    345       // Priority is always <= 65535 (enforced by sema)..
    346       PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
    347       llvm::Function *Fn =
    348         CreateGlobalInitOrDestructFunction(*this, FTy,
    349                                            "_GLOBAL__I_" + PrioritySuffix);
    350 
    351       for (; I < PrioE; ++I)
    352         LocalCXXGlobalInits.push_back(I->second);
    353 
    354       CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
    355       AddGlobalCtor(Fn, Priority);
    356     }
    357   }
    358 
    359   llvm::Function *Fn =
    360     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
    361 
    362   CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
    363   AddGlobalCtor(Fn);
    364 
    365   CXXGlobalInits.clear();
    366   PrioritizedCXXGlobalInits.clear();
    367 }
    368 
    369 void CodeGenModule::EmitCXXGlobalDtorFunc() {
    370   if (CXXGlobalDtors.empty())
    371     return;
    372 
    373   llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
    374 
    375   // Create our global destructor function.
    376   llvm::Function *Fn =
    377     CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__D_a");
    378 
    379   CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
    380   AddGlobalDtor(Fn);
    381 }
    382 
    383 /// Emit the code necessary to initialize the given global variable.
    384 void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
    385                                                        const VarDecl *D,
    386                                                  llvm::GlobalVariable *Addr,
    387                                                        bool PerformInit) {
    388   // Check if we need to emit debug info for variable initializer.
    389   if (!D->hasAttr<NoDebugAttr>())
    390     maybeInitializeDebugInfo();
    391 
    392   StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
    393                 getTypes().arrangeNullaryFunction(),
    394                 FunctionArgList(), D->getInit()->getExprLoc());
    395 
    396   // Use guarded initialization if the global variable is weak. This
    397   // occurs for, e.g., instantiated static data members and
    398   // definitions explicitly marked weak.
    399   if (Addr->getLinkage() == llvm::GlobalValue::WeakODRLinkage ||
    400       Addr->getLinkage() == llvm::GlobalValue::WeakAnyLinkage) {
    401     EmitCXXGuardedInit(*D, Addr, PerformInit);
    402   } else {
    403     EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
    404   }
    405 
    406   FinishFunction();
    407 }
    408 
    409 void
    410 CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
    411                                            ArrayRef<llvm::Constant *> Decls,
    412                                            llvm::GlobalVariable *Guard) {
    413   // Initialize debug info if needed.
    414   maybeInitializeDebugInfo();
    415 
    416   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
    417                 getTypes().arrangeNullaryFunction(),
    418                 FunctionArgList(), SourceLocation());
    419 
    420   llvm::BasicBlock *ExitBlock = 0;
    421   if (Guard) {
    422     // If we have a guard variable, check whether we've already performed these
    423     // initializations. This happens for TLS initialization functions.
    424     llvm::Value *GuardVal = Builder.CreateLoad(Guard);
    425     llvm::Value *Uninit = Builder.CreateIsNull(GuardVal, "guard.uninitialized");
    426     // Mark as initialized before initializing anything else. If the
    427     // initializers use previously-initialized thread_local vars, that's
    428     // probably supposed to be OK, but the standard doesn't say.
    429     Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(), 1), Guard);
    430     llvm::BasicBlock *InitBlock = createBasicBlock("init");
    431     ExitBlock = createBasicBlock("exit");
    432     Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
    433     EmitBlock(InitBlock);
    434   }
    435 
    436   RunCleanupsScope Scope(*this);
    437 
    438   // When building in Objective-C++ ARC mode, create an autorelease pool
    439   // around the global initializers.
    440   if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
    441     llvm::Value *token = EmitObjCAutoreleasePoolPush();
    442     EmitObjCAutoreleasePoolCleanup(token);
    443   }
    444 
    445   for (unsigned i = 0, e = Decls.size(); i != e; ++i)
    446     if (Decls[i])
    447       EmitRuntimeCall(Decls[i]);
    448 
    449   Scope.ForceCleanup();
    450 
    451   if (ExitBlock) {
    452     Builder.CreateBr(ExitBlock);
    453     EmitBlock(ExitBlock);
    454   }
    455 
    456   FinishFunction();
    457 }
    458 
    459 void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
    460                   const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
    461                                                 &DtorsAndObjects) {
    462   // Initialize debug info if needed.
    463   maybeInitializeDebugInfo();
    464 
    465   StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
    466                 getTypes().arrangeNullaryFunction(),
    467                 FunctionArgList(), SourceLocation());
    468 
    469   // Emit the dtors, in reverse order from construction.
    470   for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
    471     llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
    472     llvm::CallInst *CI = Builder.CreateCall(Callee,
    473                                             DtorsAndObjects[e - i - 1].second);
    474     // Make sure the call and the callee agree on calling convention.
    475     if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
    476       CI->setCallingConv(F->getCallingConv());
    477   }
    478 
    479   FinishFunction();
    480 }
    481 
    482 /// generateDestroyHelper - Generates a helper function which, when
    483 /// invoked, destroys the given object.
    484 llvm::Function *
    485 CodeGenFunction::generateDestroyHelper(llvm::Constant *addr,
    486                                        QualType type,
    487                                        Destroyer *destroyer,
    488                                        bool useEHCleanupForArray) {
    489   FunctionArgList args;
    490   ImplicitParamDecl dst(0, SourceLocation(), 0, getContext().VoidPtrTy);
    491   args.push_back(&dst);
    492 
    493   const CGFunctionInfo &FI =
    494     CGM.getTypes().arrangeFunctionDeclaration(getContext().VoidTy, args,
    495                                               FunctionType::ExtInfo(),
    496                                               /*variadic*/ false);
    497   llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
    498   llvm::Function *fn =
    499     CreateGlobalInitOrDestructFunction(CGM, FTy, "__cxx_global_array_dtor");
    500 
    501   // Initialize debug info if needed.
    502   maybeInitializeDebugInfo();
    503 
    504   StartFunction(GlobalDecl(), getContext().VoidTy, fn, FI, args,
    505                 SourceLocation());
    506 
    507   emitDestroy(addr, type, destroyer, useEHCleanupForArray);
    508 
    509   FinishFunction();
    510 
    511   return fn;
    512 }
    513