clang API Documentation
00001 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This coordinates the per-module state used while generating code. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "CodeGenModule.h" 00015 #include "CGDebugInfo.h" 00016 #include "CodeGenFunction.h" 00017 #include "CodeGenTBAA.h" 00018 #include "CGCall.h" 00019 #include "CGCUDARuntime.h" 00020 #include "CGCXXABI.h" 00021 #include "CGObjCRuntime.h" 00022 #include "CGOpenCLRuntime.h" 00023 #include "TargetInfo.h" 00024 #include "clang/Frontend/CodeGenOptions.h" 00025 #include "clang/AST/ASTContext.h" 00026 #include "clang/AST/CharUnits.h" 00027 #include "clang/AST/DeclObjC.h" 00028 #include "clang/AST/DeclCXX.h" 00029 #include "clang/AST/DeclTemplate.h" 00030 #include "clang/AST/Mangle.h" 00031 #include "clang/AST/RecordLayout.h" 00032 #include "clang/AST/RecursiveASTVisitor.h" 00033 #include "clang/Basic/Builtins.h" 00034 #include "clang/Basic/Diagnostic.h" 00035 #include "clang/Basic/SourceManager.h" 00036 #include "clang/Basic/TargetInfo.h" 00037 #include "clang/Basic/ConvertUTF.h" 00038 #include "llvm/CallingConv.h" 00039 #include "llvm/Module.h" 00040 #include "llvm/Intrinsics.h" 00041 #include "llvm/LLVMContext.h" 00042 #include "llvm/ADT/APSInt.h" 00043 #include "llvm/ADT/Triple.h" 00044 #include "llvm/Target/Mangler.h" 00045 #include "llvm/Target/TargetData.h" 00046 #include "llvm/Support/CallSite.h" 00047 #include "llvm/Support/ErrorHandling.h" 00048 using namespace clang; 00049 using namespace CodeGen; 00050 00051 static const char AnnotationSection[] = "llvm.metadata"; 00052 00053 static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 00054 switch (CGM.getContext().getTargetInfo().getCXXABI()) { 00055 case CXXABI_ARM: return *CreateARMCXXABI(CGM); 00056 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 00057 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 00058 } 00059 00060 llvm_unreachable("invalid C++ ABI kind"); 00061 } 00062 00063 00064 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 00065 llvm::Module &M, const llvm::TargetData &TD, 00066 DiagnosticsEngine &diags) 00067 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M), 00068 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 00069 ABI(createCXXABI(*this)), 00070 Types(*this), 00071 TBAA(0), 00072 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0), 00073 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0), 00074 RRData(0), CFConstantStringClassRef(0), 00075 ConstantStringClassRef(0), NSConstantStringType(0), 00076 VMContext(M.getContext()), 00077 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 00078 BlockObjectAssign(0), BlockObjectDispose(0), 00079 BlockDescriptorType(0), GenericBlockLiteralType(0) { 00080 00081 // Initialize the type cache. 00082 llvm::LLVMContext &LLVMContext = M.getContext(); 00083 VoidTy = llvm::Type::getVoidTy(LLVMContext); 00084 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 00085 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 00086 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 00087 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 00088 FloatTy = llvm::Type::getFloatTy(LLVMContext); 00089 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 00090 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 00091 PointerAlignInBytes = 00092 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 00093 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 00094 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits); 00095 Int8PtrTy = Int8Ty->getPointerTo(0); 00096 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 00097 00098 if (LangOpts.ObjC1) 00099 createObjCRuntime(); 00100 if (LangOpts.OpenCL) 00101 createOpenCLRuntime(); 00102 if (LangOpts.CUDA) 00103 createCUDARuntime(); 00104 00105 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 00106 if (LangOpts.ThreadSanitizer || 00107 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 00108 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(), 00109 ABI.getMangleContext()); 00110 00111 // If debug info or coverage generation is enabled, create the CGDebugInfo 00112 // object. 00113 if (CodeGenOpts.DebugInfo != CodeGenOptions::NoDebugInfo || 00114 CodeGenOpts.EmitGcovArcs || 00115 CodeGenOpts.EmitGcovNotes) 00116 DebugInfo = new CGDebugInfo(*this); 00117 00118 Block.GlobalUniqueCount = 0; 00119 00120 if (C.getLangOpts().ObjCAutoRefCount) 00121 ARCData = new ARCEntrypoints(); 00122 RRData = new RREntrypoints(); 00123 } 00124 00125 CodeGenModule::~CodeGenModule() { 00126 delete ObjCRuntime; 00127 delete OpenCLRuntime; 00128 delete CUDARuntime; 00129 delete TheTargetCodeGenInfo; 00130 delete &ABI; 00131 delete TBAA; 00132 delete DebugInfo; 00133 delete ARCData; 00134 delete RRData; 00135 } 00136 00137 void CodeGenModule::createObjCRuntime() { 00138 if (!LangOpts.NeXTRuntime) 00139 ObjCRuntime = CreateGNUObjCRuntime(*this); 00140 else 00141 ObjCRuntime = CreateMacObjCRuntime(*this); 00142 } 00143 00144 void CodeGenModule::createOpenCLRuntime() { 00145 OpenCLRuntime = new CGOpenCLRuntime(*this); 00146 } 00147 00148 void CodeGenModule::createCUDARuntime() { 00149 CUDARuntime = CreateNVCUDARuntime(*this); 00150 } 00151 00152 void CodeGenModule::Release() { 00153 EmitDeferred(); 00154 EmitCXXGlobalInitFunc(); 00155 EmitCXXGlobalDtorFunc(); 00156 if (ObjCRuntime) 00157 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 00158 AddGlobalCtor(ObjCInitFunction); 00159 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 00160 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 00161 EmitGlobalAnnotations(); 00162 EmitLLVMUsed(); 00163 00164 SimplifyPersonality(); 00165 00166 if (getCodeGenOpts().EmitDeclMetadata) 00167 EmitDeclMetadata(); 00168 00169 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 00170 EmitCoverageFile(); 00171 00172 if (DebugInfo) 00173 DebugInfo->finalize(); 00174 } 00175 00176 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 00177 // Make sure that this type is translated. 00178 Types.UpdateCompletedType(TD); 00179 } 00180 00181 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 00182 if (!TBAA) 00183 return 0; 00184 return TBAA->getTBAAInfo(QTy); 00185 } 00186 00187 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() { 00188 if (!TBAA) 00189 return 0; 00190 return TBAA->getTBAAInfoForVTablePtr(); 00191 } 00192 00193 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 00194 llvm::MDNode *TBAAInfo) { 00195 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 00196 } 00197 00198 bool CodeGenModule::isTargetDarwin() const { 00199 return getContext().getTargetInfo().getTriple().isOSDarwin(); 00200 } 00201 00202 void CodeGenModule::Error(SourceLocation loc, StringRef error) { 00203 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error); 00204 getDiags().Report(Context.getFullLoc(loc), diagID); 00205 } 00206 00207 /// ErrorUnsupported - Print out an error that codegen doesn't support the 00208 /// specified stmt yet. 00209 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 00210 bool OmitOnError) { 00211 if (OmitOnError && getDiags().hasErrorOccurred()) 00212 return; 00213 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 00214 "cannot compile this %0 yet"); 00215 std::string Msg = Type; 00216 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 00217 << Msg << S->getSourceRange(); 00218 } 00219 00220 /// ErrorUnsupported - Print out an error that codegen doesn't support the 00221 /// specified decl yet. 00222 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 00223 bool OmitOnError) { 00224 if (OmitOnError && getDiags().hasErrorOccurred()) 00225 return; 00226 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 00227 "cannot compile this %0 yet"); 00228 std::string Msg = Type; 00229 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 00230 } 00231 00232 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 00233 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 00234 } 00235 00236 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 00237 const NamedDecl *D) const { 00238 // Internal definitions always have default visibility. 00239 if (GV->hasLocalLinkage()) { 00240 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 00241 return; 00242 } 00243 00244 // Set visibility for definitions. 00245 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 00246 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage()) 00247 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 00248 } 00249 00250 /// Set the symbol visibility of type information (vtable and RTTI) 00251 /// associated with the given type. 00252 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 00253 const CXXRecordDecl *RD, 00254 TypeVisibilityKind TVK) const { 00255 setGlobalVisibility(GV, RD); 00256 00257 if (!CodeGenOpts.HiddenWeakVTables) 00258 return; 00259 00260 // We never want to drop the visibility for RTTI names. 00261 if (TVK == TVK_ForRTTIName) 00262 return; 00263 00264 // We want to drop the visibility to hidden for weak type symbols. 00265 // This isn't possible if there might be unresolved references 00266 // elsewhere that rely on this symbol being visible. 00267 00268 // This should be kept roughly in sync with setThunkVisibility 00269 // in CGVTables.cpp. 00270 00271 // Preconditions. 00272 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage || 00273 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 00274 return; 00275 00276 // Don't override an explicit visibility attribute. 00277 if (RD->getExplicitVisibility()) 00278 return; 00279 00280 switch (RD->getTemplateSpecializationKind()) { 00281 // We have to disable the optimization if this is an EI definition 00282 // because there might be EI declarations in other shared objects. 00283 case TSK_ExplicitInstantiationDefinition: 00284 case TSK_ExplicitInstantiationDeclaration: 00285 return; 00286 00287 // Every use of a non-template class's type information has to emit it. 00288 case TSK_Undeclared: 00289 break; 00290 00291 // In theory, implicit instantiations can ignore the possibility of 00292 // an explicit instantiation declaration because there necessarily 00293 // must be an EI definition somewhere with default visibility. In 00294 // practice, it's possible to have an explicit instantiation for 00295 // an arbitrary template class, and linkers aren't necessarily able 00296 // to deal with mixed-visibility symbols. 00297 case TSK_ExplicitSpecialization: 00298 case TSK_ImplicitInstantiation: 00299 if (!CodeGenOpts.HiddenWeakTemplateVTables) 00300 return; 00301 break; 00302 } 00303 00304 // If there's a key function, there may be translation units 00305 // that don't have the key function's definition. But ignore 00306 // this if we're emitting RTTI under -fno-rtti. 00307 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) { 00308 if (Context.getKeyFunction(RD)) 00309 return; 00310 } 00311 00312 // Otherwise, drop the visibility to hidden. 00313 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 00314 GV->setUnnamedAddr(true); 00315 } 00316 00317 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 00318 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 00319 00320 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 00321 if (!Str.empty()) 00322 return Str; 00323 00324 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 00325 IdentifierInfo *II = ND->getIdentifier(); 00326 assert(II && "Attempt to mangle unnamed decl."); 00327 00328 Str = II->getName(); 00329 return Str; 00330 } 00331 00332 SmallString<256> Buffer; 00333 llvm::raw_svector_ostream Out(Buffer); 00334 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 00335 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out); 00336 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 00337 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out); 00338 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 00339 getCXXABI().getMangleContext().mangleBlock(BD, Out); 00340 else 00341 getCXXABI().getMangleContext().mangleName(ND, Out); 00342 00343 // Allocate space for the mangled name. 00344 Out.flush(); 00345 size_t Length = Buffer.size(); 00346 char *Name = MangledNamesAllocator.Allocate<char>(Length); 00347 std::copy(Buffer.begin(), Buffer.end(), Name); 00348 00349 Str = StringRef(Name, Length); 00350 00351 return Str; 00352 } 00353 00354 void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer, 00355 const BlockDecl *BD) { 00356 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 00357 const Decl *D = GD.getDecl(); 00358 llvm::raw_svector_ostream Out(Buffer.getBuffer()); 00359 if (D == 0) 00360 MangleCtx.mangleGlobalBlock(BD, Out); 00361 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 00362 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 00363 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D)) 00364 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 00365 else 00366 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 00367 } 00368 00369 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 00370 return getModule().getNamedValue(Name); 00371 } 00372 00373 /// AddGlobalCtor - Add a function to the list that will be called before 00374 /// main() runs. 00375 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 00376 // FIXME: Type coercion of void()* types. 00377 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 00378 } 00379 00380 /// AddGlobalDtor - Add a function to the list that will be called 00381 /// when the module is unloaded. 00382 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 00383 // FIXME: Type coercion of void()* types. 00384 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 00385 } 00386 00387 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 00388 // Ctor function type is void()*. 00389 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 00390 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 00391 00392 // Get the type of a ctor entry, { i32, void ()* }. 00393 llvm::StructType *CtorStructTy = 00394 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL); 00395 00396 // Construct the constructor and destructor arrays. 00397 SmallVector<llvm::Constant*, 8> Ctors; 00398 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 00399 llvm::Constant *S[] = { 00400 llvm::ConstantInt::get(Int32Ty, I->second, false), 00401 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy) 00402 }; 00403 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 00404 } 00405 00406 if (!Ctors.empty()) { 00407 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 00408 new llvm::GlobalVariable(TheModule, AT, false, 00409 llvm::GlobalValue::AppendingLinkage, 00410 llvm::ConstantArray::get(AT, Ctors), 00411 GlobalName); 00412 } 00413 } 00414 00415 llvm::GlobalValue::LinkageTypes 00416 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 00417 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 00418 00419 if (Linkage == GVA_Internal) 00420 return llvm::Function::InternalLinkage; 00421 00422 if (D->hasAttr<DLLExportAttr>()) 00423 return llvm::Function::DLLExportLinkage; 00424 00425 if (D->hasAttr<WeakAttr>()) 00426 return llvm::Function::WeakAnyLinkage; 00427 00428 // In C99 mode, 'inline' functions are guaranteed to have a strong 00429 // definition somewhere else, so we can use available_externally linkage. 00430 if (Linkage == GVA_C99Inline) 00431 return llvm::Function::AvailableExternallyLinkage; 00432 00433 // Note that Apple's kernel linker doesn't support symbol 00434 // coalescing, so we need to avoid linkonce and weak linkages there. 00435 // Normally, this means we just map to internal, but for explicit 00436 // instantiations we'll map to external. 00437 00438 // In C++, the compiler has to emit a definition in every translation unit 00439 // that references the function. We should use linkonce_odr because 00440 // a) if all references in this translation unit are optimized away, we 00441 // don't need to codegen it. b) if the function persists, it needs to be 00442 // merged with other definitions. c) C++ has the ODR, so we know the 00443 // definition is dependable. 00444 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 00445 return !Context.getLangOpts().AppleKext 00446 ? llvm::Function::LinkOnceODRLinkage 00447 : llvm::Function::InternalLinkage; 00448 00449 // An explicit instantiation of a template has weak linkage, since 00450 // explicit instantiations can occur in multiple translation units 00451 // and must all be equivalent. However, we are not allowed to 00452 // throw away these explicit instantiations. 00453 if (Linkage == GVA_ExplicitTemplateInstantiation) 00454 return !Context.getLangOpts().AppleKext 00455 ? llvm::Function::WeakODRLinkage 00456 : llvm::Function::ExternalLinkage; 00457 00458 // Otherwise, we have strong external linkage. 00459 assert(Linkage == GVA_StrongExternal); 00460 return llvm::Function::ExternalLinkage; 00461 } 00462 00463 00464 /// SetFunctionDefinitionAttributes - Set attributes for a global. 00465 /// 00466 /// FIXME: This is currently only done for aliases and functions, but not for 00467 /// variables (these details are set in EmitGlobalVarDefinition for variables). 00468 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 00469 llvm::GlobalValue *GV) { 00470 SetCommonAttributes(D, GV); 00471 } 00472 00473 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 00474 const CGFunctionInfo &Info, 00475 llvm::Function *F) { 00476 unsigned CallingConv; 00477 AttributeListType AttributeList; 00478 ConstructAttributeList(Info, D, AttributeList, CallingConv); 00479 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 00480 AttributeList.size())); 00481 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 00482 } 00483 00484 /// Determines whether the language options require us to model 00485 /// unwind exceptions. We treat -fexceptions as mandating this 00486 /// except under the fragile ObjC ABI with only ObjC exceptions 00487 /// enabled. This means, for example, that C with -fexceptions 00488 /// enables this. 00489 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 00490 // If exceptions are completely disabled, obviously this is false. 00491 if (!LangOpts.Exceptions) return false; 00492 00493 // If C++ exceptions are enabled, this is true. 00494 if (LangOpts.CXXExceptions) return true; 00495 00496 // If ObjC exceptions are enabled, this depends on the ABI. 00497 if (LangOpts.ObjCExceptions) { 00498 if (!LangOpts.ObjCNonFragileABI) return false; 00499 } 00500 00501 return true; 00502 } 00503 00504 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 00505 llvm::Function *F) { 00506 if (CodeGenOpts.UnwindTables) 00507 F->setHasUWTable(); 00508 00509 if (!hasUnwindExceptions(LangOpts)) 00510 F->addFnAttr(llvm::Attribute::NoUnwind); 00511 00512 if (D->hasAttr<NakedAttr>()) { 00513 // Naked implies noinline: we should not be inlining such functions. 00514 F->addFnAttr(llvm::Attribute::Naked); 00515 F->addFnAttr(llvm::Attribute::NoInline); 00516 } 00517 00518 if (D->hasAttr<NoInlineAttr>()) 00519 F->addFnAttr(llvm::Attribute::NoInline); 00520 00521 // (noinline wins over always_inline, and we can't specify both in IR) 00522 if (D->hasAttr<AlwaysInlineAttr>() && 00523 !F->hasFnAttr(llvm::Attribute::NoInline)) 00524 F->addFnAttr(llvm::Attribute::AlwaysInline); 00525 00526 // FIXME: Communicate hot and cold attributes to LLVM more directly. 00527 if (D->hasAttr<ColdAttr>()) 00528 F->addFnAttr(llvm::Attribute::OptimizeForSize); 00529 00530 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 00531 F->setUnnamedAddr(true); 00532 00533 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 00534 F->addFnAttr(llvm::Attribute::StackProtect); 00535 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 00536 F->addFnAttr(llvm::Attribute::StackProtectReq); 00537 00538 if (LangOpts.AddressSanitizer) { 00539 // When AddressSanitizer is enabled, set AddressSafety attribute 00540 // unless __attribute__((no_address_safety_analysis)) is used. 00541 if (!D->hasAttr<NoAddressSafetyAnalysisAttr>()) 00542 F->addFnAttr(llvm::Attribute::AddressSafety); 00543 } 00544 00545 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 00546 if (alignment) 00547 F->setAlignment(alignment); 00548 00549 // C++ ABI requires 2-byte alignment for member functions. 00550 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 00551 F->setAlignment(2); 00552 } 00553 00554 void CodeGenModule::SetCommonAttributes(const Decl *D, 00555 llvm::GlobalValue *GV) { 00556 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 00557 setGlobalVisibility(GV, ND); 00558 else 00559 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 00560 00561 if (D->hasAttr<UsedAttr>()) 00562 AddUsedGlobal(GV); 00563 00564 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 00565 GV->setSection(SA->getName()); 00566 00567 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 00568 } 00569 00570 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 00571 llvm::Function *F, 00572 const CGFunctionInfo &FI) { 00573 SetLLVMFunctionAttributes(D, FI, F); 00574 SetLLVMFunctionAttributesForDefinition(D, F); 00575 00576 F->setLinkage(llvm::Function::InternalLinkage); 00577 00578 SetCommonAttributes(D, F); 00579 } 00580 00581 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 00582 llvm::Function *F, 00583 bool IsIncompleteFunction) { 00584 if (unsigned IID = F->getIntrinsicID()) { 00585 // If this is an intrinsic function, set the function's attributes 00586 // to the intrinsic's attributes. 00587 F->setAttributes(llvm::Intrinsic::getAttributes((llvm::Intrinsic::ID)IID)); 00588 return; 00589 } 00590 00591 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 00592 00593 if (!IsIncompleteFunction) 00594 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F); 00595 00596 // Only a few attributes are set on declarations; these may later be 00597 // overridden by a definition. 00598 00599 if (FD->hasAttr<DLLImportAttr>()) { 00600 F->setLinkage(llvm::Function::DLLImportLinkage); 00601 } else if (FD->hasAttr<WeakAttr>() || 00602 FD->isWeakImported()) { 00603 // "extern_weak" is overloaded in LLVM; we probably should have 00604 // separate linkage types for this. 00605 F->setLinkage(llvm::Function::ExternalWeakLinkage); 00606 } else { 00607 F->setLinkage(llvm::Function::ExternalLinkage); 00608 00609 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility(); 00610 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) { 00611 F->setVisibility(GetLLVMVisibility(LV.visibility())); 00612 } 00613 } 00614 00615 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 00616 F->setSection(SA->getName()); 00617 } 00618 00619 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 00620 assert(!GV->isDeclaration() && 00621 "Only globals with definition can force usage."); 00622 LLVMUsed.push_back(GV); 00623 } 00624 00625 void CodeGenModule::EmitLLVMUsed() { 00626 // Don't create llvm.used if there is no need. 00627 if (LLVMUsed.empty()) 00628 return; 00629 00630 // Convert LLVMUsed to what ConstantArray needs. 00631 SmallVector<llvm::Constant*, 8> UsedArray; 00632 UsedArray.resize(LLVMUsed.size()); 00633 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 00634 UsedArray[i] = 00635 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 00636 Int8PtrTy); 00637 } 00638 00639 if (UsedArray.empty()) 00640 return; 00641 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 00642 00643 llvm::GlobalVariable *GV = 00644 new llvm::GlobalVariable(getModule(), ATy, false, 00645 llvm::GlobalValue::AppendingLinkage, 00646 llvm::ConstantArray::get(ATy, UsedArray), 00647 "llvm.used"); 00648 00649 GV->setSection("llvm.metadata"); 00650 } 00651 00652 void CodeGenModule::EmitDeferred() { 00653 // Emit code for any potentially referenced deferred decls. Since a 00654 // previously unused static decl may become used during the generation of code 00655 // for a static function, iterate until no changes are made. 00656 00657 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 00658 if (!DeferredVTables.empty()) { 00659 const CXXRecordDecl *RD = DeferredVTables.back(); 00660 DeferredVTables.pop_back(); 00661 getVTables().GenerateClassData(getVTableLinkage(RD), RD); 00662 continue; 00663 } 00664 00665 GlobalDecl D = DeferredDeclsToEmit.back(); 00666 DeferredDeclsToEmit.pop_back(); 00667 00668 // Check to see if we've already emitted this. This is necessary 00669 // for a couple of reasons: first, decls can end up in the 00670 // deferred-decls queue multiple times, and second, decls can end 00671 // up with definitions in unusual ways (e.g. by an extern inline 00672 // function acquiring a strong function redefinition). Just 00673 // ignore these cases. 00674 // 00675 // TODO: That said, looking this up multiple times is very wasteful. 00676 StringRef Name = getMangledName(D); 00677 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 00678 assert(CGRef && "Deferred decl wasn't referenced?"); 00679 00680 if (!CGRef->isDeclaration()) 00681 continue; 00682 00683 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 00684 // purposes an alias counts as a definition. 00685 if (isa<llvm::GlobalAlias>(CGRef)) 00686 continue; 00687 00688 // Otherwise, emit the definition and move on to the next one. 00689 EmitGlobalDefinition(D); 00690 } 00691 } 00692 00693 void CodeGenModule::EmitGlobalAnnotations() { 00694 if (Annotations.empty()) 00695 return; 00696 00697 // Create a new global variable for the ConstantStruct in the Module. 00698 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 00699 Annotations[0]->getType(), Annotations.size()), Annotations); 00700 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), 00701 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array, 00702 "llvm.global.annotations"); 00703 gv->setSection(AnnotationSection); 00704 } 00705 00706 llvm::Constant *CodeGenModule::EmitAnnotationString(llvm::StringRef Str) { 00707 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str); 00708 if (i != AnnotationStrings.end()) 00709 return i->second; 00710 00711 // Not found yet, create a new global. 00712 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 00713 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(), 00714 true, llvm::GlobalValue::PrivateLinkage, s, ".str"); 00715 gv->setSection(AnnotationSection); 00716 gv->setUnnamedAddr(true); 00717 AnnotationStrings[Str] = gv; 00718 return gv; 00719 } 00720 00721 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 00722 SourceManager &SM = getContext().getSourceManager(); 00723 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 00724 if (PLoc.isValid()) 00725 return EmitAnnotationString(PLoc.getFilename()); 00726 return EmitAnnotationString(SM.getBufferName(Loc)); 00727 } 00728 00729 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 00730 SourceManager &SM = getContext().getSourceManager(); 00731 PresumedLoc PLoc = SM.getPresumedLoc(L); 00732 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 00733 SM.getExpansionLineNumber(L); 00734 return llvm::ConstantInt::get(Int32Ty, LineNo); 00735 } 00736 00737 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 00738 const AnnotateAttr *AA, 00739 SourceLocation L) { 00740 // Get the globals for file name, annotation, and the line number. 00741 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 00742 *UnitGV = EmitAnnotationUnit(L), 00743 *LineNoCst = EmitAnnotationLineNo(L); 00744 00745 // Create the ConstantStruct for the global annotation. 00746 llvm::Constant *Fields[4] = { 00747 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy), 00748 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 00749 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 00750 LineNoCst 00751 }; 00752 return llvm::ConstantStruct::getAnon(Fields); 00753 } 00754 00755 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 00756 llvm::GlobalValue *GV) { 00757 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 00758 // Get the struct elements for these annotations. 00759 for (specific_attr_iterator<AnnotateAttr> 00760 ai = D->specific_attr_begin<AnnotateAttr>(), 00761 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai) 00762 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation())); 00763 } 00764 00765 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 00766 // Never defer when EmitAllDecls is specified. 00767 if (LangOpts.EmitAllDecls) 00768 return false; 00769 00770 return !getContext().DeclMustBeEmitted(Global); 00771 } 00772 00773 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 00774 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 00775 assert(AA && "No alias?"); 00776 00777 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 00778 00779 // See if there is already something with the target's name in the module. 00780 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 00781 00782 llvm::Constant *Aliasee; 00783 if (isa<llvm::FunctionType>(DeclTy)) 00784 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 00785 /*ForVTable=*/false); 00786 else 00787 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 00788 llvm::PointerType::getUnqual(DeclTy), 0); 00789 if (!Entry) { 00790 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 00791 F->setLinkage(llvm::Function::ExternalWeakLinkage); 00792 WeakRefReferences.insert(F); 00793 } 00794 00795 return Aliasee; 00796 } 00797 00798 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 00799 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 00800 00801 // Weak references don't produce any output by themselves. 00802 if (Global->hasAttr<WeakRefAttr>()) 00803 return; 00804 00805 // If this is an alias definition (which otherwise looks like a declaration) 00806 // emit it now. 00807 if (Global->hasAttr<AliasAttr>()) 00808 return EmitAliasDefinition(GD); 00809 00810 // If this is CUDA, be selective about which declarations we emit. 00811 if (LangOpts.CUDA) { 00812 if (CodeGenOpts.CUDAIsDevice) { 00813 if (!Global->hasAttr<CUDADeviceAttr>() && 00814 !Global->hasAttr<CUDAGlobalAttr>() && 00815 !Global->hasAttr<CUDAConstantAttr>() && 00816 !Global->hasAttr<CUDASharedAttr>()) 00817 return; 00818 } else { 00819 if (!Global->hasAttr<CUDAHostAttr>() && ( 00820 Global->hasAttr<CUDADeviceAttr>() || 00821 Global->hasAttr<CUDAConstantAttr>() || 00822 Global->hasAttr<CUDASharedAttr>())) 00823 return; 00824 } 00825 } 00826 00827 // Ignore declarations, they will be emitted on their first use. 00828 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 00829 // Forward declarations are emitted lazily on first use. 00830 if (!FD->doesThisDeclarationHaveABody()) { 00831 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 00832 return; 00833 00834 const FunctionDecl *InlineDefinition = 0; 00835 FD->getBody(InlineDefinition); 00836 00837 StringRef MangledName = getMangledName(GD); 00838 DeferredDecls.erase(MangledName); 00839 EmitGlobalDefinition(InlineDefinition); 00840 return; 00841 } 00842 } else { 00843 const VarDecl *VD = cast<VarDecl>(Global); 00844 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 00845 00846 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 00847 return; 00848 } 00849 00850 // Defer code generation when possible if this is a static definition, inline 00851 // function etc. These we only want to emit if they are used. 00852 if (!MayDeferGeneration(Global)) { 00853 // Emit the definition if it can't be deferred. 00854 EmitGlobalDefinition(GD); 00855 return; 00856 } 00857 00858 // If we're deferring emission of a C++ variable with an 00859 // initializer, remember the order in which it appeared in the file. 00860 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 00861 cast<VarDecl>(Global)->hasInit()) { 00862 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 00863 CXXGlobalInits.push_back(0); 00864 } 00865 00866 // If the value has already been used, add it directly to the 00867 // DeferredDeclsToEmit list. 00868 StringRef MangledName = getMangledName(GD); 00869 if (GetGlobalValue(MangledName)) 00870 DeferredDeclsToEmit.push_back(GD); 00871 else { 00872 // Otherwise, remember that we saw a deferred decl with this name. The 00873 // first use of the mangled name will cause it to move into 00874 // DeferredDeclsToEmit. 00875 DeferredDecls[MangledName] = GD; 00876 } 00877 } 00878 00879 namespace { 00880 struct FunctionIsDirectlyRecursive : 00881 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> { 00882 const StringRef Name; 00883 const Builtin::Context &BI; 00884 bool Result; 00885 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) : 00886 Name(N), BI(C), Result(false) { 00887 } 00888 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base; 00889 00890 bool TraverseCallExpr(CallExpr *E) { 00891 const FunctionDecl *FD = E->getDirectCallee(); 00892 if (!FD) 00893 return true; 00894 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 00895 if (Attr && Name == Attr->getLabel()) { 00896 Result = true; 00897 return false; 00898 } 00899 unsigned BuiltinID = FD->getBuiltinID(); 00900 if (!BuiltinID) 00901 return true; 00902 StringRef BuiltinName = BI.GetName(BuiltinID); 00903 if (BuiltinName.startswith("__builtin_") && 00904 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 00905 Result = true; 00906 return false; 00907 } 00908 return true; 00909 } 00910 }; 00911 } 00912 00913 // isTriviallyRecursive - Check if this function calls another 00914 // decl that, because of the asm attribute or the other decl being a builtin, 00915 // ends up pointing to itself. 00916 bool 00917 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 00918 StringRef Name; 00919 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 00920 // asm labels are a special kind of mangling we have to support. 00921 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 00922 if (!Attr) 00923 return false; 00924 Name = Attr->getLabel(); 00925 } else { 00926 Name = FD->getName(); 00927 } 00928 00929 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 00930 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD)); 00931 return Walker.Result; 00932 } 00933 00934 bool 00935 CodeGenModule::shouldEmitFunction(const FunctionDecl *F) { 00936 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage) 00937 return true; 00938 if (CodeGenOpts.OptimizationLevel == 0 && 00939 !F->hasAttr<AlwaysInlineAttr>()) 00940 return false; 00941 // PR9614. Avoid cases where the source code is lying to us. An available 00942 // externally function should have an equivalent function somewhere else, 00943 // but a function that calls itself is clearly not equivalent to the real 00944 // implementation. 00945 // This happens in glibc's btowc and in some configure checks. 00946 return !isTriviallyRecursive(F); 00947 } 00948 00949 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 00950 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 00951 00952 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 00953 Context.getSourceManager(), 00954 "Generating code for declaration"); 00955 00956 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 00957 // At -O0, don't generate IR for functions with available_externally 00958 // linkage. 00959 if (!shouldEmitFunction(Function)) 00960 return; 00961 00962 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 00963 // Make sure to emit the definition(s) before we emit the thunks. 00964 // This is necessary for the generation of certain thunks. 00965 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 00966 EmitCXXConstructor(CD, GD.getCtorType()); 00967 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method)) 00968 EmitCXXDestructor(DD, GD.getDtorType()); 00969 else 00970 EmitGlobalFunctionDefinition(GD); 00971 00972 if (Method->isVirtual()) 00973 getVTables().EmitThunks(GD); 00974 00975 return; 00976 } 00977 00978 return EmitGlobalFunctionDefinition(GD); 00979 } 00980 00981 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 00982 return EmitGlobalVarDefinition(VD); 00983 00984 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 00985 } 00986 00987 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 00988 /// module, create and return an llvm Function with the specified type. If there 00989 /// is something in the module with the specified name, return it potentially 00990 /// bitcasted to the right type. 00991 /// 00992 /// If D is non-null, it specifies a decl that correspond to this. This is used 00993 /// to set the attributes on the function when it is first created. 00994 llvm::Constant * 00995 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName, 00996 llvm::Type *Ty, 00997 GlobalDecl D, bool ForVTable, 00998 llvm::Attributes ExtraAttrs) { 00999 // Lookup the entry, lazily creating it if necessary. 01000 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 01001 if (Entry) { 01002 if (WeakRefReferences.count(Entry)) { 01003 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 01004 if (FD && !FD->hasAttr<WeakAttr>()) 01005 Entry->setLinkage(llvm::Function::ExternalLinkage); 01006 01007 WeakRefReferences.erase(Entry); 01008 } 01009 01010 if (Entry->getType()->getElementType() == Ty) 01011 return Entry; 01012 01013 // Make sure the result is of the correct type. 01014 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 01015 } 01016 01017 // This function doesn't have a complete type (for example, the return 01018 // type is an incomplete struct). Use a fake type instead, and make 01019 // sure not to try to set attributes. 01020 bool IsIncompleteFunction = false; 01021 01022 llvm::FunctionType *FTy; 01023 if (isa<llvm::FunctionType>(Ty)) { 01024 FTy = cast<llvm::FunctionType>(Ty); 01025 } else { 01026 FTy = llvm::FunctionType::get(VoidTy, false); 01027 IsIncompleteFunction = true; 01028 } 01029 01030 llvm::Function *F = llvm::Function::Create(FTy, 01031 llvm::Function::ExternalLinkage, 01032 MangledName, &getModule()); 01033 assert(F->getName() == MangledName && "name was uniqued!"); 01034 if (D.getDecl()) 01035 SetFunctionAttributes(D, F, IsIncompleteFunction); 01036 if (ExtraAttrs != llvm::Attribute::None) 01037 F->addFnAttr(ExtraAttrs); 01038 01039 // This is the first use or definition of a mangled name. If there is a 01040 // deferred decl with this name, remember that we need to emit it at the end 01041 // of the file. 01042 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 01043 if (DDI != DeferredDecls.end()) { 01044 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 01045 // list, and remove it from DeferredDecls (since we don't need it anymore). 01046 DeferredDeclsToEmit.push_back(DDI->second); 01047 DeferredDecls.erase(DDI); 01048 01049 // Otherwise, there are cases we have to worry about where we're 01050 // using a declaration for which we must emit a definition but where 01051 // we might not find a top-level definition: 01052 // - member functions defined inline in their classes 01053 // - friend functions defined inline in some class 01054 // - special member functions with implicit definitions 01055 // If we ever change our AST traversal to walk into class methods, 01056 // this will be unnecessary. 01057 // 01058 // We also don't emit a definition for a function if it's going to be an entry 01059 // in a vtable, unless it's already marked as used. 01060 } else if (getLangOpts().CPlusPlus && D.getDecl()) { 01061 // Look for a declaration that's lexically in a record. 01062 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl()); 01063 do { 01064 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 01065 if (FD->isImplicit() && !ForVTable) { 01066 assert(FD->isUsed() && "Sema didn't mark implicit function as used!"); 01067 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 01068 break; 01069 } else if (FD->doesThisDeclarationHaveABody()) { 01070 DeferredDeclsToEmit.push_back(D.getWithDecl(FD)); 01071 break; 01072 } 01073 } 01074 FD = FD->getPreviousDecl(); 01075 } while (FD); 01076 } 01077 01078 // Make sure the result is of the requested type. 01079 if (!IsIncompleteFunction) { 01080 assert(F->getType()->getElementType() == Ty); 01081 return F; 01082 } 01083 01084 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 01085 return llvm::ConstantExpr::getBitCast(F, PTy); 01086 } 01087 01088 /// GetAddrOfFunction - Return the address of the given function. If Ty is 01089 /// non-null, then this function will use the specified type if it has to 01090 /// create it (this occurs when we see a definition of the function). 01091 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 01092 llvm::Type *Ty, 01093 bool ForVTable) { 01094 // If there was no specific requested type, just convert it now. 01095 if (!Ty) 01096 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 01097 01098 StringRef MangledName = getMangledName(GD); 01099 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable); 01100 } 01101 01102 /// CreateRuntimeFunction - Create a new runtime function with the specified 01103 /// type and name. 01104 llvm::Constant * 01105 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, 01106 StringRef Name, 01107 llvm::Attributes ExtraAttrs) { 01108 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 01109 ExtraAttrs); 01110 } 01111 01112 /// isTypeConstant - Determine whether an object of this type can be emitted 01113 /// as a constant. 01114 /// 01115 /// If ExcludeCtor is true, the duration when the object's constructor runs 01116 /// will not be considered. The caller will need to verify that the object is 01117 /// not written to during its construction. 01118 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 01119 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 01120 return false; 01121 01122 if (Context.getLangOpts().CPlusPlus) { 01123 if (const CXXRecordDecl *Record 01124 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 01125 return ExcludeCtor && !Record->hasMutableFields() && 01126 Record->hasTrivialDestructor(); 01127 } 01128 01129 return true; 01130 } 01131 01132 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 01133 /// create and return an llvm GlobalVariable with the specified type. If there 01134 /// is something in the module with the specified name, return it potentially 01135 /// bitcasted to the right type. 01136 /// 01137 /// If D is non-null, it specifies a decl that correspond to this. This is used 01138 /// to set the attributes on the global when it is first created. 01139 llvm::Constant * 01140 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 01141 llvm::PointerType *Ty, 01142 const VarDecl *D, 01143 bool UnnamedAddr) { 01144 // Lookup the entry, lazily creating it if necessary. 01145 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 01146 if (Entry) { 01147 if (WeakRefReferences.count(Entry)) { 01148 if (D && !D->hasAttr<WeakAttr>()) 01149 Entry->setLinkage(llvm::Function::ExternalLinkage); 01150 01151 WeakRefReferences.erase(Entry); 01152 } 01153 01154 if (UnnamedAddr) 01155 Entry->setUnnamedAddr(true); 01156 01157 if (Entry->getType() == Ty) 01158 return Entry; 01159 01160 // Make sure the result is of the correct type. 01161 return llvm::ConstantExpr::getBitCast(Entry, Ty); 01162 } 01163 01164 // This is the first use or definition of a mangled name. If there is a 01165 // deferred decl with this name, remember that we need to emit it at the end 01166 // of the file. 01167 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 01168 if (DDI != DeferredDecls.end()) { 01169 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 01170 // list, and remove it from DeferredDecls (since we don't need it anymore). 01171 DeferredDeclsToEmit.push_back(DDI->second); 01172 DeferredDecls.erase(DDI); 01173 } 01174 01175 llvm::GlobalVariable *GV = 01176 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 01177 llvm::GlobalValue::ExternalLinkage, 01178 0, MangledName, 0, 01179 false, Ty->getAddressSpace()); 01180 01181 // Handle things which are present even on external declarations. 01182 if (D) { 01183 // FIXME: This code is overly simple and should be merged with other global 01184 // handling. 01185 GV->setConstant(isTypeConstant(D->getType(), false)); 01186 01187 // Set linkage and visibility in case we never see a definition. 01188 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility(); 01189 if (LV.linkage() != ExternalLinkage) { 01190 // Don't set internal linkage on declarations. 01191 } else { 01192 if (D->hasAttr<DLLImportAttr>()) 01193 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 01194 else if (D->hasAttr<WeakAttr>() || D->isWeakImported()) 01195 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 01196 01197 // Set visibility on a declaration only if it's explicit. 01198 if (LV.visibilityExplicit()) 01199 GV->setVisibility(GetLLVMVisibility(LV.visibility())); 01200 } 01201 01202 GV->setThreadLocal(D->isThreadSpecified()); 01203 } 01204 01205 return GV; 01206 } 01207 01208 01209 llvm::GlobalVariable * 01210 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name, 01211 llvm::Type *Ty, 01212 llvm::GlobalValue::LinkageTypes Linkage) { 01213 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 01214 llvm::GlobalVariable *OldGV = 0; 01215 01216 01217 if (GV) { 01218 // Check if the variable has the right type. 01219 if (GV->getType()->getElementType() == Ty) 01220 return GV; 01221 01222 // Because C++ name mangling, the only way we can end up with an already 01223 // existing global with the same name is if it has been declared extern "C". 01224 assert(GV->isDeclaration() && "Declaration has wrong type!"); 01225 OldGV = GV; 01226 } 01227 01228 // Create a new variable. 01229 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 01230 Linkage, 0, Name); 01231 01232 if (OldGV) { 01233 // Replace occurrences of the old variable if needed. 01234 GV->takeName(OldGV); 01235 01236 if (!OldGV->use_empty()) { 01237 llvm::Constant *NewPtrForOldDecl = 01238 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 01239 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 01240 } 01241 01242 OldGV->eraseFromParent(); 01243 } 01244 01245 return GV; 01246 } 01247 01248 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 01249 /// given global variable. If Ty is non-null and if the global doesn't exist, 01250 /// then it will be created with the specified type instead of whatever the 01251 /// normal requested type would be. 01252 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 01253 llvm::Type *Ty) { 01254 assert(D->hasGlobalStorage() && "Not a global variable"); 01255 QualType ASTTy = D->getType(); 01256 if (Ty == 0) 01257 Ty = getTypes().ConvertTypeForMem(ASTTy); 01258 01259 llvm::PointerType *PTy = 01260 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 01261 01262 StringRef MangledName = getMangledName(D); 01263 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 01264 } 01265 01266 /// CreateRuntimeVariable - Create a new runtime global variable with the 01267 /// specified type and name. 01268 llvm::Constant * 01269 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 01270 StringRef Name) { 01271 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0, 01272 true); 01273 } 01274 01275 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 01276 assert(!D->getInit() && "Cannot emit definite definitions here!"); 01277 01278 if (MayDeferGeneration(D)) { 01279 // If we have not seen a reference to this variable yet, place it 01280 // into the deferred declarations table to be emitted if needed 01281 // later. 01282 StringRef MangledName = getMangledName(D); 01283 if (!GetGlobalValue(MangledName)) { 01284 DeferredDecls[MangledName] = D; 01285 return; 01286 } 01287 } 01288 01289 // The tentative definition is the only definition. 01290 EmitGlobalVarDefinition(D); 01291 } 01292 01293 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 01294 if (DefinitionRequired) 01295 getVTables().GenerateClassData(getVTableLinkage(Class), Class); 01296 } 01297 01298 llvm::GlobalVariable::LinkageTypes 01299 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 01300 if (RD->getLinkage() != ExternalLinkage) 01301 return llvm::GlobalVariable::InternalLinkage; 01302 01303 if (const CXXMethodDecl *KeyFunction 01304 = RD->getASTContext().getKeyFunction(RD)) { 01305 // If this class has a key function, use that to determine the linkage of 01306 // the vtable. 01307 const FunctionDecl *Def = 0; 01308 if (KeyFunction->hasBody(Def)) 01309 KeyFunction = cast<CXXMethodDecl>(Def); 01310 01311 switch (KeyFunction->getTemplateSpecializationKind()) { 01312 case TSK_Undeclared: 01313 case TSK_ExplicitSpecialization: 01314 // When compiling with optimizations turned on, we emit all vtables, 01315 // even if the key function is not defined in the current translation 01316 // unit. If this is the case, use available_externally linkage. 01317 if (!Def && CodeGenOpts.OptimizationLevel) 01318 return llvm::GlobalVariable::AvailableExternallyLinkage; 01319 01320 if (KeyFunction->isInlined()) 01321 return !Context.getLangOpts().AppleKext ? 01322 llvm::GlobalVariable::LinkOnceODRLinkage : 01323 llvm::Function::InternalLinkage; 01324 01325 return llvm::GlobalVariable::ExternalLinkage; 01326 01327 case TSK_ImplicitInstantiation: 01328 return !Context.getLangOpts().AppleKext ? 01329 llvm::GlobalVariable::LinkOnceODRLinkage : 01330 llvm::Function::InternalLinkage; 01331 01332 case TSK_ExplicitInstantiationDefinition: 01333 return !Context.getLangOpts().AppleKext ? 01334 llvm::GlobalVariable::WeakODRLinkage : 01335 llvm::Function::InternalLinkage; 01336 01337 case TSK_ExplicitInstantiationDeclaration: 01338 // FIXME: Use available_externally linkage. However, this currently 01339 // breaks LLVM's build due to undefined symbols. 01340 // return llvm::GlobalVariable::AvailableExternallyLinkage; 01341 return !Context.getLangOpts().AppleKext ? 01342 llvm::GlobalVariable::LinkOnceODRLinkage : 01343 llvm::Function::InternalLinkage; 01344 } 01345 } 01346 01347 if (Context.getLangOpts().AppleKext) 01348 return llvm::Function::InternalLinkage; 01349 01350 switch (RD->getTemplateSpecializationKind()) { 01351 case TSK_Undeclared: 01352 case TSK_ExplicitSpecialization: 01353 case TSK_ImplicitInstantiation: 01354 // FIXME: Use available_externally linkage. However, this currently 01355 // breaks LLVM's build due to undefined symbols. 01356 // return llvm::GlobalVariable::AvailableExternallyLinkage; 01357 case TSK_ExplicitInstantiationDeclaration: 01358 return llvm::GlobalVariable::LinkOnceODRLinkage; 01359 01360 case TSK_ExplicitInstantiationDefinition: 01361 return llvm::GlobalVariable::WeakODRLinkage; 01362 } 01363 01364 llvm_unreachable("Invalid TemplateSpecializationKind!"); 01365 } 01366 01367 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 01368 return Context.toCharUnitsFromBits( 01369 TheTargetData.getTypeStoreSizeInBits(Ty)); 01370 } 01371 01372 llvm::Constant * 01373 CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D, 01374 const Expr *rawInit) { 01375 ArrayRef<ExprWithCleanups::CleanupObject> cleanups; 01376 if (const ExprWithCleanups *withCleanups = 01377 dyn_cast<ExprWithCleanups>(rawInit)) { 01378 cleanups = withCleanups->getObjects(); 01379 rawInit = withCleanups->getSubExpr(); 01380 } 01381 01382 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit); 01383 if (!init || !init->initializesStdInitializerList() || 01384 init->getNumInits() == 0) 01385 return 0; 01386 01387 ASTContext &ctx = getContext(); 01388 unsigned numInits = init->getNumInits(); 01389 // FIXME: This check is here because we would otherwise silently miscompile 01390 // nested global std::initializer_lists. Better would be to have a real 01391 // implementation. 01392 for (unsigned i = 0; i < numInits; ++i) { 01393 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i)); 01394 if (inner && inner->initializesStdInitializerList()) { 01395 ErrorUnsupported(inner, "nested global std::initializer_list"); 01396 return 0; 01397 } 01398 } 01399 01400 // Synthesize a fake VarDecl for the array and initialize that. 01401 QualType elementType = init->getInit(0)->getType(); 01402 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits); 01403 QualType arrayType = ctx.getConstantArrayType(elementType, numElements, 01404 ArrayType::Normal, 0); 01405 01406 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist"); 01407 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo( 01408 arrayType, D->getLocation()); 01409 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>( 01410 D->getDeclContext()), 01411 D->getLocStart(), D->getLocation(), 01412 name, arrayType, sourceInfo, 01413 SC_Static, SC_Static); 01414 01415 // Now clone the InitListExpr to initialize the array instead. 01416 // Incredible hack: we want to use the existing InitListExpr here, so we need 01417 // to tell it that it no longer initializes a std::initializer_list. 01418 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), 01419 const_cast<InitListExpr*>(init)->getInits(), 01420 init->getNumInits(), 01421 init->getRBraceLoc()); 01422 arrayInit->setType(arrayType); 01423 01424 if (!cleanups.empty()) 01425 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups); 01426 01427 backingArray->setInit(arrayInit); 01428 01429 // Emit the definition of the array. 01430 EmitGlobalVarDefinition(backingArray); 01431 01432 // Inspect the initializer list to validate it and determine its type. 01433 // FIXME: doing this every time is probably inefficient; caching would be nice 01434 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl(); 01435 RecordDecl::field_iterator field = record->field_begin(); 01436 if (field == record->field_end()) { 01437 ErrorUnsupported(D, "weird std::initializer_list"); 01438 return 0; 01439 } 01440 QualType elementPtr = ctx.getPointerType(elementType.withConst()); 01441 // Start pointer. 01442 if (!ctx.hasSameType(field->getType(), elementPtr)) { 01443 ErrorUnsupported(D, "weird std::initializer_list"); 01444 return 0; 01445 } 01446 ++field; 01447 if (field == record->field_end()) { 01448 ErrorUnsupported(D, "weird std::initializer_list"); 01449 return 0; 01450 } 01451 bool isStartEnd = false; 01452 if (ctx.hasSameType(field->getType(), elementPtr)) { 01453 // End pointer. 01454 isStartEnd = true; 01455 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) { 01456 ErrorUnsupported(D, "weird std::initializer_list"); 01457 return 0; 01458 } 01459 01460 // Now build an APValue representing the std::initializer_list. 01461 APValue initListValue(APValue::UninitStruct(), 0, 2); 01462 APValue &startField = initListValue.getStructField(0); 01463 APValue::LValuePathEntry startOffsetPathEntry; 01464 startOffsetPathEntry.ArrayIndex = 0; 01465 startField = APValue(APValue::LValueBase(backingArray), 01466 CharUnits::fromQuantity(0), 01467 llvm::makeArrayRef(startOffsetPathEntry), 01468 /*IsOnePastTheEnd=*/false, 0); 01469 01470 if (isStartEnd) { 01471 APValue &endField = initListValue.getStructField(1); 01472 APValue::LValuePathEntry endOffsetPathEntry; 01473 endOffsetPathEntry.ArrayIndex = numInits; 01474 endField = APValue(APValue::LValueBase(backingArray), 01475 ctx.getTypeSizeInChars(elementType) * numInits, 01476 llvm::makeArrayRef(endOffsetPathEntry), 01477 /*IsOnePastTheEnd=*/true, 0); 01478 } else { 01479 APValue &sizeField = initListValue.getStructField(1); 01480 sizeField = APValue(llvm::APSInt(numElements)); 01481 } 01482 01483 // Emit the constant for the initializer_list. 01484 llvm::Constant *llvmInit = 01485 EmitConstantValueForMemory(initListValue, D->getType()); 01486 assert(llvmInit && "failed to initialize as constant"); 01487 return llvmInit; 01488 } 01489 01490 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 01491 llvm::Constant *Init = 0; 01492 QualType ASTTy = D->getType(); 01493 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 01494 bool NeedsGlobalCtor = false; 01495 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor(); 01496 01497 const VarDecl *InitDecl; 01498 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 01499 01500 if (!InitExpr) { 01501 // This is a tentative definition; tentative definitions are 01502 // implicitly initialized with { 0 }. 01503 // 01504 // Note that tentative definitions are only emitted at the end of 01505 // a translation unit, so they should never have incomplete 01506 // type. In addition, EmitTentativeDefinition makes sure that we 01507 // never attempt to emit a tentative definition if a real one 01508 // exists. A use may still exists, however, so we still may need 01509 // to do a RAUW. 01510 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 01511 Init = EmitNullConstant(D->getType()); 01512 } else { 01513 // If this is a std::initializer_list, emit the special initializer. 01514 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr); 01515 // An empty init list will perform zero-initialization, which happens 01516 // to be exactly what we want. 01517 // FIXME: It does so in a global constructor, which is *not* what we 01518 // want. 01519 01520 if (!Init) 01521 Init = EmitConstantInit(*InitDecl); 01522 if (!Init) { 01523 QualType T = InitExpr->getType(); 01524 if (D->getType()->isReferenceType()) 01525 T = D->getType(); 01526 01527 if (getLangOpts().CPlusPlus) { 01528 Init = EmitNullConstant(T); 01529 NeedsGlobalCtor = true; 01530 } else { 01531 ErrorUnsupported(D, "static initializer"); 01532 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 01533 } 01534 } else { 01535 // We don't need an initializer, so remove the entry for the delayed 01536 // initializer position (just in case this entry was delayed) if we 01537 // also don't need to register a destructor. 01538 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 01539 DelayedCXXInitPosition.erase(D); 01540 } 01541 } 01542 01543 llvm::Type* InitType = Init->getType(); 01544 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 01545 01546 // Strip off a bitcast if we got one back. 01547 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 01548 assert(CE->getOpcode() == llvm::Instruction::BitCast || 01549 // all zero index gep. 01550 CE->getOpcode() == llvm::Instruction::GetElementPtr); 01551 Entry = CE->getOperand(0); 01552 } 01553 01554 // Entry is now either a Function or GlobalVariable. 01555 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 01556 01557 // We have a definition after a declaration with the wrong type. 01558 // We must make a new GlobalVariable* and update everything that used OldGV 01559 // (a declaration or tentative definition) with the new GlobalVariable* 01560 // (which will be a definition). 01561 // 01562 // This happens if there is a prototype for a global (e.g. 01563 // "extern int x[];") and then a definition of a different type (e.g. 01564 // "int x[10];"). This also happens when an initializer has a different type 01565 // from the type of the global (this happens with unions). 01566 if (GV == 0 || 01567 GV->getType()->getElementType() != InitType || 01568 GV->getType()->getAddressSpace() != 01569 getContext().getTargetAddressSpace(ASTTy)) { 01570 01571 // Move the old entry aside so that we'll create a new one. 01572 Entry->setName(StringRef()); 01573 01574 // Make a new global with the correct type, this is now guaranteed to work. 01575 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 01576 01577 // Replace all uses of the old global with the new global 01578 llvm::Constant *NewPtrForOldDecl = 01579 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 01580 Entry->replaceAllUsesWith(NewPtrForOldDecl); 01581 01582 // Erase the old global, since it is no longer used. 01583 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 01584 } 01585 01586 if (D->hasAttr<AnnotateAttr>()) 01587 AddGlobalAnnotations(D, GV); 01588 01589 GV->setInitializer(Init); 01590 01591 // If it is safe to mark the global 'constant', do so now. 01592 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 01593 isTypeConstant(D->getType(), true)); 01594 01595 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 01596 01597 // Set the llvm linkage type as appropriate. 01598 llvm::GlobalValue::LinkageTypes Linkage = 01599 GetLLVMLinkageVarDefinition(D, GV); 01600 GV->setLinkage(Linkage); 01601 if (Linkage == llvm::GlobalVariable::CommonLinkage) 01602 // common vars aren't constant even if declared const. 01603 GV->setConstant(false); 01604 01605 SetCommonAttributes(D, GV); 01606 01607 // Emit the initializer function if necessary. 01608 if (NeedsGlobalCtor || NeedsGlobalDtor) 01609 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 01610 01611 // Emit global variable debug information. 01612 if (CGDebugInfo *DI = getModuleDebugInfo()) 01613 if (getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) 01614 DI->EmitGlobalVariable(GV, D); 01615 } 01616 01617 llvm::GlobalValue::LinkageTypes 01618 CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D, 01619 llvm::GlobalVariable *GV) { 01620 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 01621 if (Linkage == GVA_Internal) 01622 return llvm::Function::InternalLinkage; 01623 else if (D->hasAttr<DLLImportAttr>()) 01624 return llvm::Function::DLLImportLinkage; 01625 else if (D->hasAttr<DLLExportAttr>()) 01626 return llvm::Function::DLLExportLinkage; 01627 else if (D->hasAttr<WeakAttr>()) { 01628 if (GV->isConstant()) 01629 return llvm::GlobalVariable::WeakODRLinkage; 01630 else 01631 return llvm::GlobalVariable::WeakAnyLinkage; 01632 } else if (Linkage == GVA_TemplateInstantiation || 01633 Linkage == GVA_ExplicitTemplateInstantiation) 01634 return llvm::GlobalVariable::WeakODRLinkage; 01635 else if (!getLangOpts().CPlusPlus && 01636 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) || 01637 D->getAttr<CommonAttr>()) && 01638 !D->hasExternalStorage() && !D->getInit() && 01639 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() && 01640 !D->getAttr<WeakImportAttr>()) { 01641 // Thread local vars aren't considered common linkage. 01642 return llvm::GlobalVariable::CommonLinkage; 01643 } 01644 return llvm::GlobalVariable::ExternalLinkage; 01645 } 01646 01647 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 01648 /// implement a function with no prototype, e.g. "int foo() {}". If there are 01649 /// existing call uses of the old function in the module, this adjusts them to 01650 /// call the new function directly. 01651 /// 01652 /// This is not just a cleanup: the always_inline pass requires direct calls to 01653 /// functions to be able to inline them. If there is a bitcast in the way, it 01654 /// won't inline them. Instcombine normally deletes these calls, but it isn't 01655 /// run at -O0. 01656 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 01657 llvm::Function *NewFn) { 01658 // If we're redefining a global as a function, don't transform it. 01659 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 01660 if (OldFn == 0) return; 01661 01662 llvm::Type *NewRetTy = NewFn->getReturnType(); 01663 SmallVector<llvm::Value*, 4> ArgList; 01664 01665 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 01666 UI != E; ) { 01667 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 01668 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 01669 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 01670 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 01671 llvm::CallSite CS(CI); 01672 if (!CI || !CS.isCallee(I)) continue; 01673 01674 // If the return types don't match exactly, and if the call isn't dead, then 01675 // we can't transform this call. 01676 if (CI->getType() != NewRetTy && !CI->use_empty()) 01677 continue; 01678 01679 // Get the attribute list. 01680 llvm::SmallVector<llvm::AttributeWithIndex, 8> AttrVec; 01681 llvm::AttrListPtr AttrList = CI->getAttributes(); 01682 01683 // Get any return attributes. 01684 llvm::Attributes RAttrs = AttrList.getRetAttributes(); 01685 01686 // Add the return attributes. 01687 if (RAttrs) 01688 AttrVec.push_back(llvm::AttributeWithIndex::get(0, RAttrs)); 01689 01690 // If the function was passed too few arguments, don't transform. If extra 01691 // arguments were passed, we silently drop them. If any of the types 01692 // mismatch, we don't transform. 01693 unsigned ArgNo = 0; 01694 bool DontTransform = false; 01695 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 01696 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 01697 if (CS.arg_size() == ArgNo || 01698 CS.getArgument(ArgNo)->getType() != AI->getType()) { 01699 DontTransform = true; 01700 break; 01701 } 01702 01703 // Add any parameter attributes. 01704 if (llvm::Attributes PAttrs = AttrList.getParamAttributes(ArgNo + 1)) 01705 AttrVec.push_back(llvm::AttributeWithIndex::get(ArgNo + 1, PAttrs)); 01706 } 01707 if (DontTransform) 01708 continue; 01709 01710 if (llvm::Attributes FnAttrs = AttrList.getFnAttributes()) 01711 AttrVec.push_back(llvm::AttributeWithIndex::get(~0, FnAttrs)); 01712 01713 // Okay, we can transform this. Create the new call instruction and copy 01714 // over the required information. 01715 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 01716 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList, "", CI); 01717 ArgList.clear(); 01718 if (!NewCall->getType()->isVoidTy()) 01719 NewCall->takeName(CI); 01720 NewCall->setAttributes(llvm::AttrListPtr::get(AttrVec.begin(), 01721 AttrVec.end())); 01722 NewCall->setCallingConv(CI->getCallingConv()); 01723 01724 // Finally, remove the old call, replacing any uses with the new one. 01725 if (!CI->use_empty()) 01726 CI->replaceAllUsesWith(NewCall); 01727 01728 // Copy debug location attached to CI. 01729 if (!CI->getDebugLoc().isUnknown()) 01730 NewCall->setDebugLoc(CI->getDebugLoc()); 01731 CI->eraseFromParent(); 01732 } 01733 } 01734 01735 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 01736 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 01737 // If we have a definition, this might be a deferred decl. If the 01738 // instantiation is explicit, make sure we emit it at the end. 01739 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 01740 GetAddrOfGlobalVar(VD); 01741 } 01742 01743 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 01744 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 01745 01746 // Compute the function info and LLVM type. 01747 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 01748 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 01749 01750 // Get or create the prototype for the function. 01751 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 01752 01753 // Strip off a bitcast if we got one back. 01754 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 01755 assert(CE->getOpcode() == llvm::Instruction::BitCast); 01756 Entry = CE->getOperand(0); 01757 } 01758 01759 01760 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 01761 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 01762 01763 // If the types mismatch then we have to rewrite the definition. 01764 assert(OldFn->isDeclaration() && 01765 "Shouldn't replace non-declaration"); 01766 01767 // F is the Function* for the one with the wrong type, we must make a new 01768 // Function* and update everything that used F (a declaration) with the new 01769 // Function* (which will be a definition). 01770 // 01771 // This happens if there is a prototype for a function 01772 // (e.g. "int f()") and then a definition of a different type 01773 // (e.g. "int f(int x)"). Move the old function aside so that it 01774 // doesn't interfere with GetAddrOfFunction. 01775 OldFn->setName(StringRef()); 01776 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 01777 01778 // If this is an implementation of a function without a prototype, try to 01779 // replace any existing uses of the function (which may be calls) with uses 01780 // of the new function 01781 if (D->getType()->isFunctionNoProtoType()) { 01782 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 01783 OldFn->removeDeadConstantUsers(); 01784 } 01785 01786 // Replace uses of F with the Function we will endow with a body. 01787 if (!Entry->use_empty()) { 01788 llvm::Constant *NewPtrForOldDecl = 01789 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 01790 Entry->replaceAllUsesWith(NewPtrForOldDecl); 01791 } 01792 01793 // Ok, delete the old function now, which is dead. 01794 OldFn->eraseFromParent(); 01795 01796 Entry = NewFn; 01797 } 01798 01799 // We need to set linkage and visibility on the function before 01800 // generating code for it because various parts of IR generation 01801 // want to propagate this information down (e.g. to local static 01802 // declarations). 01803 llvm::Function *Fn = cast<llvm::Function>(Entry); 01804 setFunctionLinkage(D, Fn); 01805 01806 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes 01807 setGlobalVisibility(Fn, D); 01808 01809 CodeGenFunction(*this).GenerateCode(D, Fn, FI); 01810 01811 SetFunctionDefinitionAttributes(D, Fn); 01812 SetLLVMFunctionAttributesForDefinition(D, Fn); 01813 01814 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 01815 AddGlobalCtor(Fn, CA->getPriority()); 01816 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 01817 AddGlobalDtor(Fn, DA->getPriority()); 01818 if (D->hasAttr<AnnotateAttr>()) 01819 AddGlobalAnnotations(D, Fn); 01820 } 01821 01822 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 01823 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 01824 const AliasAttr *AA = D->getAttr<AliasAttr>(); 01825 assert(AA && "Not an alias?"); 01826 01827 StringRef MangledName = getMangledName(GD); 01828 01829 // If there is a definition in the module, then it wins over the alias. 01830 // This is dubious, but allow it to be safe. Just ignore the alias. 01831 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 01832 if (Entry && !Entry->isDeclaration()) 01833 return; 01834 01835 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 01836 01837 // Create a reference to the named value. This ensures that it is emitted 01838 // if a deferred decl. 01839 llvm::Constant *Aliasee; 01840 if (isa<llvm::FunctionType>(DeclTy)) 01841 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl(), 01842 /*ForVTable=*/false); 01843 else 01844 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 01845 llvm::PointerType::getUnqual(DeclTy), 0); 01846 01847 // Create the new alias itself, but don't set a name yet. 01848 llvm::GlobalValue *GA = 01849 new llvm::GlobalAlias(Aliasee->getType(), 01850 llvm::Function::ExternalLinkage, 01851 "", Aliasee, &getModule()); 01852 01853 if (Entry) { 01854 assert(Entry->isDeclaration()); 01855 01856 // If there is a declaration in the module, then we had an extern followed 01857 // by the alias, as in: 01858 // extern int test6(); 01859 // ... 01860 // int test6() __attribute__((alias("test7"))); 01861 // 01862 // Remove it and replace uses of it with the alias. 01863 GA->takeName(Entry); 01864 01865 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 01866 Entry->getType())); 01867 Entry->eraseFromParent(); 01868 } else { 01869 GA->setName(MangledName); 01870 } 01871 01872 // Set attributes which are particular to an alias; this is a 01873 // specialization of the attributes which may be set on a global 01874 // variable/function. 01875 if (D->hasAttr<DLLExportAttr>()) { 01876 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 01877 // The dllexport attribute is ignored for undefined symbols. 01878 if (FD->hasBody()) 01879 GA->setLinkage(llvm::Function::DLLExportLinkage); 01880 } else { 01881 GA->setLinkage(llvm::Function::DLLExportLinkage); 01882 } 01883 } else if (D->hasAttr<WeakAttr>() || 01884 D->hasAttr<WeakRefAttr>() || 01885 D->isWeakImported()) { 01886 GA->setLinkage(llvm::Function::WeakAnyLinkage); 01887 } 01888 01889 SetCommonAttributes(D, GA); 01890 } 01891 01892 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 01893 ArrayRef<llvm::Type*> Tys) { 01894 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 01895 Tys); 01896 } 01897 01898 static llvm::StringMapEntry<llvm::Constant*> & 01899 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 01900 const StringLiteral *Literal, 01901 bool TargetIsLSB, 01902 bool &IsUTF16, 01903 unsigned &StringLength) { 01904 StringRef String = Literal->getString(); 01905 unsigned NumBytes = String.size(); 01906 01907 // Check for simple case. 01908 if (!Literal->containsNonAsciiOrNull()) { 01909 StringLength = NumBytes; 01910 return Map.GetOrCreateValue(String); 01911 } 01912 01913 // Otherwise, convert the UTF8 literals into a string of shorts. 01914 IsUTF16 = true; 01915 01916 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 01917 const UTF8 *FromPtr = (UTF8 *)String.data(); 01918 UTF16 *ToPtr = &ToBuf[0]; 01919 01920 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 01921 &ToPtr, ToPtr + NumBytes, 01922 strictConversion); 01923 01924 // ConvertUTF8toUTF16 returns the length in ToPtr. 01925 StringLength = ToPtr - &ToBuf[0]; 01926 01927 // Add an explicit null. 01928 *ToPtr = 0; 01929 return Map. 01930 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()), 01931 (StringLength + 1) * 2)); 01932 } 01933 01934 static llvm::StringMapEntry<llvm::Constant*> & 01935 GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map, 01936 const StringLiteral *Literal, 01937 unsigned &StringLength) { 01938 StringRef String = Literal->getString(); 01939 StringLength = String.size(); 01940 return Map.GetOrCreateValue(String); 01941 } 01942 01943 llvm::Constant * 01944 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 01945 unsigned StringLength = 0; 01946 bool isUTF16 = false; 01947 llvm::StringMapEntry<llvm::Constant*> &Entry = 01948 GetConstantCFStringEntry(CFConstantStringMap, Literal, 01949 getTargetData().isLittleEndian(), 01950 isUTF16, StringLength); 01951 01952 if (llvm::Constant *C = Entry.getValue()) 01953 return C; 01954 01955 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 01956 llvm::Constant *Zeros[] = { Zero, Zero }; 01957 01958 // If we don't already have it, get __CFConstantStringClassReference. 01959 if (!CFConstantStringClassRef) { 01960 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 01961 Ty = llvm::ArrayType::get(Ty, 0); 01962 llvm::Constant *GV = CreateRuntimeVariable(Ty, 01963 "__CFConstantStringClassReference"); 01964 // Decay array -> ptr 01965 CFConstantStringClassRef = 01966 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 01967 } 01968 01969 QualType CFTy = getContext().getCFConstantStringType(); 01970 01971 llvm::StructType *STy = 01972 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 01973 01974 llvm::Constant *Fields[4]; 01975 01976 // Class pointer. 01977 Fields[0] = CFConstantStringClassRef; 01978 01979 // Flags. 01980 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 01981 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 01982 llvm::ConstantInt::get(Ty, 0x07C8); 01983 01984 // String pointer. 01985 llvm::Constant *C = 0; 01986 if (isUTF16) { 01987 ArrayRef<uint16_t> Arr = 01988 llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(), 01989 Entry.getKey().size() / 2); 01990 C = llvm::ConstantDataArray::get(VMContext, Arr); 01991 } else { 01992 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 01993 } 01994 01995 llvm::GlobalValue::LinkageTypes Linkage; 01996 if (isUTF16) 01997 // FIXME: why do utf strings get "_" labels instead of "L" labels? 01998 Linkage = llvm::GlobalValue::InternalLinkage; 01999 else 02000 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error 02001 // when using private linkage. It is not clear if this is a bug in ld 02002 // or a reasonable new restriction. 02003 Linkage = llvm::GlobalValue::LinkerPrivateLinkage; 02004 02005 // Note: -fwritable-strings doesn't make the backing store strings of 02006 // CFStrings writable. (See <rdar://problem/10657500>) 02007 llvm::GlobalVariable *GV = 02008 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 02009 Linkage, C, ".str"); 02010 GV->setUnnamedAddr(true); 02011 if (isUTF16) { 02012 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 02013 GV->setAlignment(Align.getQuantity()); 02014 } else { 02015 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 02016 GV->setAlignment(Align.getQuantity()); 02017 } 02018 02019 // String. 02020 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 02021 02022 if (isUTF16) 02023 // Cast the UTF16 string to the correct type. 02024 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy); 02025 02026 // String length. 02027 Ty = getTypes().ConvertType(getContext().LongTy); 02028 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 02029 02030 // The struct. 02031 C = llvm::ConstantStruct::get(STy, Fields); 02032 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 02033 llvm::GlobalVariable::PrivateLinkage, C, 02034 "_unnamed_cfstring_"); 02035 if (const char *Sect = getContext().getTargetInfo().getCFStringSection()) 02036 GV->setSection(Sect); 02037 Entry.setValue(GV); 02038 02039 return GV; 02040 } 02041 02042 static RecordDecl * 02043 CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 02044 DeclContext *DC, IdentifierInfo *Id) { 02045 SourceLocation Loc; 02046 if (Ctx.getLangOpts().CPlusPlus) 02047 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 02048 else 02049 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 02050 } 02051 02052 llvm::Constant * 02053 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) { 02054 unsigned StringLength = 0; 02055 llvm::StringMapEntry<llvm::Constant*> &Entry = 02056 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength); 02057 02058 if (llvm::Constant *C = Entry.getValue()) 02059 return C; 02060 02061 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 02062 llvm::Constant *Zeros[] = { Zero, Zero }; 02063 02064 // If we don't already have it, get _NSConstantStringClassReference. 02065 if (!ConstantStringClassRef) { 02066 std::string StringClass(getLangOpts().ObjCConstantStringClass); 02067 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 02068 llvm::Constant *GV; 02069 if (LangOpts.ObjCNonFragileABI) { 02070 std::string str = 02071 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString" 02072 : "OBJC_CLASS_$_" + StringClass; 02073 GV = getObjCRuntime().GetClassGlobal(str); 02074 // Make sure the result is of the correct type. 02075 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 02076 ConstantStringClassRef = 02077 llvm::ConstantExpr::getBitCast(GV, PTy); 02078 } else { 02079 std::string str = 02080 StringClass.empty() ? "_NSConstantStringClassReference" 02081 : "_" + StringClass + "ClassReference"; 02082 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0); 02083 GV = CreateRuntimeVariable(PTy, str); 02084 // Decay array -> ptr 02085 ConstantStringClassRef = 02086 llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 02087 } 02088 } 02089 02090 if (!NSConstantStringType) { 02091 // Construct the type for a constant NSString. 02092 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 02093 Context.getTranslationUnitDecl(), 02094 &Context.Idents.get("__builtin_NSString")); 02095 D->startDefinition(); 02096 02097 QualType FieldTypes[3]; 02098 02099 // const int *isa; 02100 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst()); 02101 // const char *str; 02102 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst()); 02103 // unsigned int length; 02104 FieldTypes[2] = Context.UnsignedIntTy; 02105 02106 // Create fields 02107 for (unsigned i = 0; i < 3; ++i) { 02108 FieldDecl *Field = FieldDecl::Create(Context, D, 02109 SourceLocation(), 02110 SourceLocation(), 0, 02111 FieldTypes[i], /*TInfo=*/0, 02112 /*BitWidth=*/0, 02113 /*Mutable=*/false, 02114 /*HasInit=*/false); 02115 Field->setAccess(AS_public); 02116 D->addDecl(Field); 02117 } 02118 02119 D->completeDefinition(); 02120 QualType NSTy = Context.getTagDeclType(D); 02121 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 02122 } 02123 02124 llvm::Constant *Fields[3]; 02125 02126 // Class pointer. 02127 Fields[0] = ConstantStringClassRef; 02128 02129 // String pointer. 02130 llvm::Constant *C = 02131 llvm::ConstantDataArray::getString(VMContext, Entry.getKey()); 02132 02133 llvm::GlobalValue::LinkageTypes Linkage; 02134 bool isConstant; 02135 Linkage = llvm::GlobalValue::PrivateLinkage; 02136 isConstant = !LangOpts.WritableStrings; 02137 02138 llvm::GlobalVariable *GV = 02139 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 02140 ".str"); 02141 GV->setUnnamedAddr(true); 02142 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy); 02143 GV->setAlignment(Align.getQuantity()); 02144 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros); 02145 02146 // String length. 02147 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 02148 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 02149 02150 // The struct. 02151 C = llvm::ConstantStruct::get(NSConstantStringType, Fields); 02152 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 02153 llvm::GlobalVariable::PrivateLinkage, C, 02154 "_unnamed_nsstring_"); 02155 // FIXME. Fix section. 02156 if (const char *Sect = 02157 LangOpts.ObjCNonFragileABI 02158 ? getContext().getTargetInfo().getNSStringNonFragileABISection() 02159 : getContext().getTargetInfo().getNSStringSection()) 02160 GV->setSection(Sect); 02161 Entry.setValue(GV); 02162 02163 return GV; 02164 } 02165 02166 QualType CodeGenModule::getObjCFastEnumerationStateType() { 02167 if (ObjCFastEnumerationStateType.isNull()) { 02168 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct, 02169 Context.getTranslationUnitDecl(), 02170 &Context.Idents.get("__objcFastEnumerationState")); 02171 D->startDefinition(); 02172 02173 QualType FieldTypes[] = { 02174 Context.UnsignedLongTy, 02175 Context.getPointerType(Context.getObjCIdType()), 02176 Context.getPointerType(Context.UnsignedLongTy), 02177 Context.getConstantArrayType(Context.UnsignedLongTy, 02178 llvm::APInt(32, 5), ArrayType::Normal, 0) 02179 }; 02180 02181 for (size_t i = 0; i < 4; ++i) { 02182 FieldDecl *Field = FieldDecl::Create(Context, 02183 D, 02184 SourceLocation(), 02185 SourceLocation(), 0, 02186 FieldTypes[i], /*TInfo=*/0, 02187 /*BitWidth=*/0, 02188 /*Mutable=*/false, 02189 /*HasInit=*/false); 02190 Field->setAccess(AS_public); 02191 D->addDecl(Field); 02192 } 02193 02194 D->completeDefinition(); 02195 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 02196 } 02197 02198 return ObjCFastEnumerationStateType; 02199 } 02200 02201 llvm::Constant * 02202 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 02203 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 02204 02205 // Don't emit it as the address of the string, emit the string data itself 02206 // as an inline array. 02207 if (E->getCharByteWidth() == 1) { 02208 SmallString<64> Str(E->getString()); 02209 02210 // Resize the string to the right size, which is indicated by its type. 02211 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 02212 Str.resize(CAT->getSize().getZExtValue()); 02213 return llvm::ConstantDataArray::getString(VMContext, Str, false); 02214 } 02215 02216 llvm::ArrayType *AType = 02217 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 02218 llvm::Type *ElemTy = AType->getElementType(); 02219 unsigned NumElements = AType->getNumElements(); 02220 02221 // Wide strings have either 2-byte or 4-byte elements. 02222 if (ElemTy->getPrimitiveSizeInBits() == 16) { 02223 SmallVector<uint16_t, 32> Elements; 02224 Elements.reserve(NumElements); 02225 02226 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 02227 Elements.push_back(E->getCodeUnit(i)); 02228 Elements.resize(NumElements); 02229 return llvm::ConstantDataArray::get(VMContext, Elements); 02230 } 02231 02232 assert(ElemTy->getPrimitiveSizeInBits() == 32); 02233 SmallVector<uint32_t, 32> Elements; 02234 Elements.reserve(NumElements); 02235 02236 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 02237 Elements.push_back(E->getCodeUnit(i)); 02238 Elements.resize(NumElements); 02239 return llvm::ConstantDataArray::get(VMContext, Elements); 02240 } 02241 02242 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 02243 /// constant array for the given string literal. 02244 llvm::Constant * 02245 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 02246 CharUnits Align = getContext().getTypeAlignInChars(S->getType()); 02247 if (S->isAscii() || S->isUTF8()) { 02248 SmallString<64> Str(S->getString()); 02249 02250 // Resize the string to the right size, which is indicated by its type. 02251 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); 02252 Str.resize(CAT->getSize().getZExtValue()); 02253 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity()); 02254 } 02255 02256 // FIXME: the following does not memoize wide strings. 02257 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 02258 llvm::GlobalVariable *GV = 02259 new llvm::GlobalVariable(getModule(),C->getType(), 02260 !LangOpts.WritableStrings, 02261 llvm::GlobalValue::PrivateLinkage, 02262 C,".str"); 02263 02264 GV->setAlignment(Align.getQuantity()); 02265 GV->setUnnamedAddr(true); 02266 return GV; 02267 } 02268 02269 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 02270 /// array for the given ObjCEncodeExpr node. 02271 llvm::Constant * 02272 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 02273 std::string Str; 02274 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 02275 02276 return GetAddrOfConstantCString(Str); 02277 } 02278 02279 02280 /// GenerateWritableString -- Creates storage for a string literal. 02281 static llvm::GlobalVariable *GenerateStringLiteral(StringRef str, 02282 bool constant, 02283 CodeGenModule &CGM, 02284 const char *GlobalName, 02285 unsigned Alignment) { 02286 // Create Constant for this string literal. Don't add a '\0'. 02287 llvm::Constant *C = 02288 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false); 02289 02290 // Create a global variable for this string 02291 llvm::GlobalVariable *GV = 02292 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 02293 llvm::GlobalValue::PrivateLinkage, 02294 C, GlobalName); 02295 GV->setAlignment(Alignment); 02296 GV->setUnnamedAddr(true); 02297 return GV; 02298 } 02299 02300 /// GetAddrOfConstantString - Returns a pointer to a character array 02301 /// containing the literal. This contents are exactly that of the 02302 /// given string, i.e. it will not be null terminated automatically; 02303 /// see GetAddrOfConstantCString. Note that whether the result is 02304 /// actually a pointer to an LLVM constant depends on 02305 /// Feature.WriteableStrings. 02306 /// 02307 /// The result has pointer to array type. 02308 llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str, 02309 const char *GlobalName, 02310 unsigned Alignment) { 02311 // Get the default prefix if a name wasn't specified. 02312 if (!GlobalName) 02313 GlobalName = ".str"; 02314 02315 // Don't share any string literals if strings aren't constant. 02316 if (LangOpts.WritableStrings) 02317 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment); 02318 02319 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 02320 ConstantStringMap.GetOrCreateValue(Str); 02321 02322 if (llvm::GlobalVariable *GV = Entry.getValue()) { 02323 if (Alignment > GV->getAlignment()) { 02324 GV->setAlignment(Alignment); 02325 } 02326 return GV; 02327 } 02328 02329 // Create a global variable for this. 02330 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName, 02331 Alignment); 02332 Entry.setValue(GV); 02333 return GV; 02334 } 02335 02336 /// GetAddrOfConstantCString - Returns a pointer to a character 02337 /// array containing the literal and a terminating '\0' 02338 /// character. The result has pointer to array type. 02339 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str, 02340 const char *GlobalName, 02341 unsigned Alignment) { 02342 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 02343 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment); 02344 } 02345 02346 /// EmitObjCPropertyImplementations - Emit information for synthesized 02347 /// properties for an implementation. 02348 void CodeGenModule::EmitObjCPropertyImplementations(const 02349 ObjCImplementationDecl *D) { 02350 for (ObjCImplementationDecl::propimpl_iterator 02351 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 02352 ObjCPropertyImplDecl *PID = &*i; 02353 02354 // Dynamic is just for type-checking. 02355 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 02356 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 02357 02358 // Determine which methods need to be implemented, some may have 02359 // been overridden. Note that ::isSynthesized is not the method 02360 // we want, that just indicates if the decl came from a 02361 // property. What we want to know is if the method is defined in 02362 // this implementation. 02363 if (!D->getInstanceMethod(PD->getGetterName())) 02364 CodeGenFunction(*this).GenerateObjCGetter( 02365 const_cast<ObjCImplementationDecl *>(D), PID); 02366 if (!PD->isReadOnly() && 02367 !D->getInstanceMethod(PD->getSetterName())) 02368 CodeGenFunction(*this).GenerateObjCSetter( 02369 const_cast<ObjCImplementationDecl *>(D), PID); 02370 } 02371 } 02372 } 02373 02374 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 02375 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 02376 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 02377 ivar; ivar = ivar->getNextIvar()) 02378 if (ivar->getType().isDestructedType()) 02379 return true; 02380 02381 return false; 02382 } 02383 02384 /// EmitObjCIvarInitializations - Emit information for ivar initialization 02385 /// for an implementation. 02386 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 02387 // We might need a .cxx_destruct even if we don't have any ivar initializers. 02388 if (needsDestructMethod(D)) { 02389 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 02390 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 02391 ObjCMethodDecl *DTORMethod = 02392 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(), 02393 cxxSelector, getContext().VoidTy, 0, D, 02394 /*isInstance=*/true, /*isVariadic=*/false, 02395 /*isSynthesized=*/true, /*isImplicitlyDeclared=*/true, 02396 /*isDefined=*/false, ObjCMethodDecl::Required); 02397 D->addInstanceMethod(DTORMethod); 02398 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 02399 D->setHasCXXStructors(true); 02400 } 02401 02402 // If the implementation doesn't have any ivar initializers, we don't need 02403 // a .cxx_construct. 02404 if (D->getNumIvarInitializers() == 0) 02405 return; 02406 02407 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 02408 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 02409 // The constructor returns 'self'. 02410 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 02411 D->getLocation(), 02412 D->getLocation(), 02413 cxxSelector, 02414 getContext().getObjCIdType(), 0, 02415 D, /*isInstance=*/true, 02416 /*isVariadic=*/false, 02417 /*isSynthesized=*/true, 02418 /*isImplicitlyDeclared=*/true, 02419 /*isDefined=*/false, 02420 ObjCMethodDecl::Required); 02421 D->addInstanceMethod(CTORMethod); 02422 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 02423 D->setHasCXXStructors(true); 02424 } 02425 02426 /// EmitNamespace - Emit all declarations in a namespace. 02427 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 02428 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 02429 I != E; ++I) 02430 EmitTopLevelDecl(*I); 02431 } 02432 02433 // EmitLinkageSpec - Emit all declarations in a linkage spec. 02434 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 02435 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 02436 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 02437 ErrorUnsupported(LSD, "linkage spec"); 02438 return; 02439 } 02440 02441 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 02442 I != E; ++I) 02443 EmitTopLevelDecl(*I); 02444 } 02445 02446 /// EmitTopLevelDecl - Emit code for a single top level declaration. 02447 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 02448 // If an error has occurred, stop code generation, but continue 02449 // parsing and semantic analysis (to ensure all warnings and errors 02450 // are emitted). 02451 if (Diags.hasErrorOccurred()) 02452 return; 02453 02454 // Ignore dependent declarations. 02455 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 02456 return; 02457 02458 switch (D->getKind()) { 02459 case Decl::CXXConversion: 02460 case Decl::CXXMethod: 02461 case Decl::Function: 02462 // Skip function templates 02463 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 02464 cast<FunctionDecl>(D)->isLateTemplateParsed()) 02465 return; 02466 02467 EmitGlobal(cast<FunctionDecl>(D)); 02468 break; 02469 02470 case Decl::Var: 02471 EmitGlobal(cast<VarDecl>(D)); 02472 break; 02473 02474 // Indirect fields from global anonymous structs and unions can be 02475 // ignored; only the actual variable requires IR gen support. 02476 case Decl::IndirectField: 02477 break; 02478 02479 // C++ Decls 02480 case Decl::Namespace: 02481 EmitNamespace(cast<NamespaceDecl>(D)); 02482 break; 02483 // No code generation needed. 02484 case Decl::UsingShadow: 02485 case Decl::Using: 02486 case Decl::UsingDirective: 02487 case Decl::ClassTemplate: 02488 case Decl::FunctionTemplate: 02489 case Decl::TypeAliasTemplate: 02490 case Decl::NamespaceAlias: 02491 case Decl::Block: 02492 case Decl::Import: 02493 break; 02494 case Decl::CXXConstructor: 02495 // Skip function templates 02496 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() || 02497 cast<FunctionDecl>(D)->isLateTemplateParsed()) 02498 return; 02499 02500 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 02501 break; 02502 case Decl::CXXDestructor: 02503 if (cast<FunctionDecl>(D)->isLateTemplateParsed()) 02504 return; 02505 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 02506 break; 02507 02508 case Decl::StaticAssert: 02509 // Nothing to do. 02510 break; 02511 02512 // Objective-C Decls 02513 02514 // Forward declarations, no (immediate) code generation. 02515 case Decl::ObjCInterface: 02516 break; 02517 02518 case Decl::ObjCCategory: { 02519 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 02520 if (CD->IsClassExtension() && CD->hasSynthBitfield()) 02521 Context.ResetObjCLayout(CD->getClassInterface()); 02522 break; 02523 } 02524 02525 case Decl::ObjCProtocol: { 02526 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D); 02527 if (Proto->isThisDeclarationADefinition()) 02528 ObjCRuntime->GenerateProtocol(Proto); 02529 break; 02530 } 02531 02532 case Decl::ObjCCategoryImpl: 02533 // Categories have properties but don't support synthesize so we 02534 // can ignore them here. 02535 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 02536 break; 02537 02538 case Decl::ObjCImplementation: { 02539 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 02540 if (LangOpts.ObjCNonFragileABI2 && OMD->hasSynthBitfield()) 02541 Context.ResetObjCLayout(OMD->getClassInterface()); 02542 EmitObjCPropertyImplementations(OMD); 02543 EmitObjCIvarInitializations(OMD); 02544 ObjCRuntime->GenerateClass(OMD); 02545 // Emit global variable debug information. 02546 if (CGDebugInfo *DI = getModuleDebugInfo()) 02547 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(OMD->getClassInterface()), 02548 OMD->getLocation()); 02549 02550 break; 02551 } 02552 case Decl::ObjCMethod: { 02553 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 02554 // If this is not a prototype, emit the body. 02555 if (OMD->getBody()) 02556 CodeGenFunction(*this).GenerateObjCMethod(OMD); 02557 break; 02558 } 02559 case Decl::ObjCCompatibleAlias: 02560 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 02561 break; 02562 02563 case Decl::LinkageSpec: 02564 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 02565 break; 02566 02567 case Decl::FileScopeAsm: { 02568 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 02569 StringRef AsmString = AD->getAsmString()->getString(); 02570 02571 const std::string &S = getModule().getModuleInlineAsm(); 02572 if (S.empty()) 02573 getModule().setModuleInlineAsm(AsmString); 02574 else if (*--S.end() == '\n') 02575 getModule().setModuleInlineAsm(S + AsmString.str()); 02576 else 02577 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 02578 break; 02579 } 02580 02581 default: 02582 // Make sure we handled everything we should, every other kind is a 02583 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 02584 // function. Need to recode Decl::Kind to do that easily. 02585 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 02586 } 02587 } 02588 02589 /// Turns the given pointer into a constant. 02590 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 02591 const void *Ptr) { 02592 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 02593 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 02594 return llvm::ConstantInt::get(i64, PtrInt); 02595 } 02596 02597 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 02598 llvm::NamedMDNode *&GlobalMetadata, 02599 GlobalDecl D, 02600 llvm::GlobalValue *Addr) { 02601 if (!GlobalMetadata) 02602 GlobalMetadata = 02603 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 02604 02605 // TODO: should we report variant information for ctors/dtors? 02606 llvm::Value *Ops[] = { 02607 Addr, 02608 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 02609 }; 02610 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 02611 } 02612 02613 /// Emits metadata nodes associating all the global values in the 02614 /// current module with the Decls they came from. This is useful for 02615 /// projects using IR gen as a subroutine. 02616 /// 02617 /// Since there's currently no way to associate an MDNode directly 02618 /// with an llvm::GlobalValue, we create a global named metadata 02619 /// with the name 'clang.global.decl.ptrs'. 02620 void CodeGenModule::EmitDeclMetadata() { 02621 llvm::NamedMDNode *GlobalMetadata = 0; 02622 02623 // StaticLocalDeclMap 02624 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator 02625 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 02626 I != E; ++I) { 02627 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 02628 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 02629 } 02630 } 02631 02632 /// Emits metadata nodes for all the local variables in the current 02633 /// function. 02634 void CodeGenFunction::EmitDeclMetadata() { 02635 if (LocalDeclMap.empty()) return; 02636 02637 llvm::LLVMContext &Context = getLLVMContext(); 02638 02639 // Find the unique metadata ID for this name. 02640 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 02641 02642 llvm::NamedMDNode *GlobalMetadata = 0; 02643 02644 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 02645 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 02646 const Decl *D = I->first; 02647 llvm::Value *Addr = I->second; 02648 02649 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 02650 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 02651 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr)); 02652 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 02653 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 02654 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 02655 } 02656 } 02657 } 02658 02659 void CodeGenModule::EmitCoverageFile() { 02660 if (!getCodeGenOpts().CoverageFile.empty()) { 02661 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) { 02662 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 02663 llvm::LLVMContext &Ctx = TheModule.getContext(); 02664 llvm::MDString *CoverageFile = 02665 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile); 02666 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 02667 llvm::MDNode *CU = CUNode->getOperand(i); 02668 llvm::Value *node[] = { CoverageFile, CU }; 02669 llvm::MDNode *N = llvm::MDNode::get(Ctx, node); 02670 GCov->addOperand(N); 02671 } 02672 } 02673 } 02674 }