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