1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This coordinates the per-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenModule.h" 15 #include "CGDebugInfo.h" 16 #include "CodeGenFunction.h" 17 #include "CodeGenTBAA.h" 18 #include "CGCall.h" 19 #include "CGCXXABI.h" 20 #include "CGObjCRuntime.h" 21 #include "Mangle.h" 22 #include "TargetInfo.h" 23 #include "clang/Frontend/CodeGenOptions.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/CharUnits.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/AST/DeclCXX.h" 28 #include "clang/AST/DeclTemplate.h" 29 #include "clang/AST/RecordLayout.h" 30 #include "clang/Basic/Builtins.h" 31 #include "clang/Basic/Diagnostic.h" 32 #include "clang/Basic/SourceManager.h" 33 #include "clang/Basic/TargetInfo.h" 34 #include "clang/Basic/ConvertUTF.h" 35 #include "llvm/CallingConv.h" 36 #include "llvm/Module.h" 37 #include "llvm/Intrinsics.h" 38 #include "llvm/LLVMContext.h" 39 #include "llvm/ADT/Triple.h" 40 #include "llvm/Target/TargetData.h" 41 #include "llvm/Support/CallSite.h" 42 #include "llvm/Support/ErrorHandling.h" 43 using namespace clang; 44 using namespace CodeGen; 45 46 static CGCXXABI &createCXXABI(CodeGenModule &CGM) { 47 switch (CGM.getContext().Target.getCXXABI()) { 48 case CXXABI_ARM: return *CreateARMCXXABI(CGM); 49 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM); 50 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM); 51 } 52 53 llvm_unreachable("invalid C++ ABI kind"); 54 return *CreateItaniumCXXABI(CGM); 55 } 56 57 58 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO, 59 llvm::Module &M, const llvm::TargetData &TD, 60 Diagnostic &diags) 61 : BlockModule(C, M, TD, Types, *this), Context(C), 62 Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M), 63 TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags), 64 ABI(createCXXABI(*this)), 65 Types(C, M, TD, getTargetCodeGenInfo().getABIInfo(), ABI), 66 TBAA(0), 67 VTables(*this), Runtime(0), 68 CFConstantStringClassRef(0), NSConstantStringClassRef(0), 69 VMContext(M.getContext()), 70 NSConcreteGlobalBlockDecl(0), NSConcreteStackBlockDecl(0), 71 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0), 72 BlockObjectAssignDecl(0), BlockObjectDisposeDecl(0), 73 BlockObjectAssign(0), BlockObjectDispose(0){ 74 75 if (!Features.ObjC1) 76 Runtime = 0; 77 else if (!Features.NeXTRuntime) 78 Runtime = CreateGNUObjCRuntime(*this); 79 else if (Features.ObjCNonFragileABI) 80 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 81 else 82 Runtime = CreateMacObjCRuntime(*this); 83 84 // Enable TBAA unless it's suppressed. 85 if (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0) 86 TBAA = new CodeGenTBAA(Context, VMContext, getLangOptions()); 87 88 // If debug info generation is enabled, create the CGDebugInfo object. 89 DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0; 90 } 91 92 CodeGenModule::~CodeGenModule() { 93 delete Runtime; 94 delete &ABI; 95 delete DebugInfo; 96 } 97 98 void CodeGenModule::createObjCRuntime() { 99 if (!Features.NeXTRuntime) 100 Runtime = CreateGNUObjCRuntime(*this); 101 else if (Features.ObjCNonFragileABI) 102 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 103 else 104 Runtime = CreateMacObjCRuntime(*this); 105 } 106 107 void CodeGenModule::Release() { 108 EmitDeferred(); 109 EmitCXXGlobalInitFunc(); 110 EmitCXXGlobalDtorFunc(); 111 if (Runtime) 112 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 113 AddGlobalCtor(ObjCInitFunction); 114 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 115 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 116 EmitAnnotations(); 117 EmitLLVMUsed(); 118 119 SimplifyPersonality(); 120 121 if (getCodeGenOpts().EmitDeclMetadata) 122 EmitDeclMetadata(); 123 } 124 125 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) { 126 if (!TBAA) 127 return 0; 128 return TBAA->getTBAAInfo(QTy); 129 } 130 131 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst, 132 llvm::MDNode *TBAAInfo) { 133 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo); 134 } 135 136 bool CodeGenModule::isTargetDarwin() const { 137 return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin; 138 } 139 140 /// ErrorUnsupported - Print out an error that codegen doesn't support the 141 /// specified stmt yet. 142 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 143 bool OmitOnError) { 144 if (OmitOnError && getDiags().hasErrorOccurred()) 145 return; 146 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 147 "cannot compile this %0 yet"); 148 std::string Msg = Type; 149 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 150 << Msg << S->getSourceRange(); 151 } 152 153 /// ErrorUnsupported - Print out an error that codegen doesn't support the 154 /// specified decl yet. 155 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 156 bool OmitOnError) { 157 if (OmitOnError && getDiags().hasErrorOccurred()) 158 return; 159 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 160 "cannot compile this %0 yet"); 161 std::string Msg = Type; 162 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 163 } 164 165 LangOptions::VisibilityMode 166 CodeGenModule::getDeclVisibilityMode(const Decl *D) const { 167 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 168 if (VD->getStorageClass() == SC_PrivateExtern) 169 return LangOptions::Hidden; 170 171 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) { 172 switch (attr->getVisibility()) { 173 default: assert(0 && "Unknown visibility!"); 174 case VisibilityAttr::Default: 175 return LangOptions::Default; 176 case VisibilityAttr::Hidden: 177 return LangOptions::Hidden; 178 case VisibilityAttr::Protected: 179 return LangOptions::Protected; 180 } 181 } 182 183 if (getLangOptions().CPlusPlus) { 184 // Entities subject to an explicit instantiation declaration get default 185 // visibility. 186 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 187 if (Function->getTemplateSpecializationKind() 188 == TSK_ExplicitInstantiationDeclaration) 189 return LangOptions::Default; 190 } else if (const ClassTemplateSpecializationDecl *ClassSpec 191 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 192 if (ClassSpec->getSpecializationKind() 193 == TSK_ExplicitInstantiationDeclaration) 194 return LangOptions::Default; 195 } else if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 196 if (Record->getTemplateSpecializationKind() 197 == TSK_ExplicitInstantiationDeclaration) 198 return LangOptions::Default; 199 } else if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 200 if (Var->isStaticDataMember() && 201 (Var->getTemplateSpecializationKind() 202 == TSK_ExplicitInstantiationDeclaration)) 203 return LangOptions::Default; 204 } 205 206 // If -fvisibility-inlines-hidden was provided, then inline C++ member 207 // functions get "hidden" visibility by default. 208 if (getLangOptions().InlineVisibilityHidden) 209 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 210 if (Method->isInlined()) 211 return LangOptions::Hidden; 212 } 213 214 // If this decl is contained in a class, it should have the same visibility 215 // as the parent class. 216 if (const DeclContext *DC = D->getDeclContext()) 217 if (DC->isRecord()) 218 return getDeclVisibilityMode(cast<Decl>(DC)); 219 220 return getLangOptions().getVisibilityMode(); 221 } 222 223 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 224 const Decl *D) const { 225 // Internal definitions always have default visibility. 226 if (GV->hasLocalLinkage()) { 227 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 228 return; 229 } 230 231 switch (getDeclVisibilityMode(D)) { 232 default: assert(0 && "Unknown visibility!"); 233 case LangOptions::Default: 234 return GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 235 case LangOptions::Hidden: 236 return GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 237 case LangOptions::Protected: 238 return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 239 } 240 } 241 242 /// Set the symbol visibility of type information (vtable and RTTI) 243 /// associated with the given type. 244 void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV, 245 const CXXRecordDecl *RD, 246 bool IsForRTTI) const { 247 setGlobalVisibility(GV, RD); 248 249 if (!CodeGenOpts.HiddenWeakVTables) 250 return; 251 252 // We want to drop the visibility to hidden for weak type symbols. 253 // This isn't possible if there might be unresolved references 254 // elsewhere that rely on this symbol being visible. 255 256 // This should be kept roughly in sync with setThunkVisibility 257 // in CGVTables.cpp. 258 259 // Preconditions. 260 if (GV->getLinkage() != llvm::GlobalVariable::WeakODRLinkage || 261 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility) 262 return; 263 264 // Don't override an explicit visibility attribute. 265 if (RD->hasAttr<VisibilityAttr>()) 266 return; 267 268 switch (RD->getTemplateSpecializationKind()) { 269 // We have to disable the optimization if this is an EI definition 270 // because there might be EI declarations in other shared objects. 271 case TSK_ExplicitInstantiationDefinition: 272 case TSK_ExplicitInstantiationDeclaration: 273 return; 274 275 // Every use of a non-template class's type information has to emit it. 276 case TSK_Undeclared: 277 break; 278 279 // In theory, implicit instantiations can ignore the possibility of 280 // an explicit instantiation declaration because there necessarily 281 // must be an EI definition somewhere with default visibility. In 282 // practice, it's possible to have an explicit instantiation for 283 // an arbitrary template class, and linkers aren't necessarily able 284 // to deal with mixed-visibility symbols. 285 case TSK_ExplicitSpecialization: 286 case TSK_ImplicitInstantiation: 287 if (!CodeGenOpts.HiddenWeakTemplateVTables) 288 return; 289 break; 290 } 291 292 // If there's a key function, there may be translation units 293 // that don't have the key function's definition. But ignore 294 // this if we're emitting RTTI under -fno-rtti. 295 if (!IsForRTTI || Features.RTTI) 296 if (Context.getKeyFunction(RD)) 297 return; 298 299 // Otherwise, drop the visibility to hidden. 300 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 301 } 302 303 llvm::StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 304 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 305 306 llvm::StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()]; 307 if (!Str.empty()) 308 return Str; 309 310 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) { 311 IdentifierInfo *II = ND->getIdentifier(); 312 assert(II && "Attempt to mangle unnamed decl."); 313 314 Str = II->getName(); 315 return Str; 316 } 317 318 llvm::SmallString<256> Buffer; 319 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND)) 320 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Buffer); 321 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND)) 322 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Buffer); 323 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND)) 324 getCXXABI().getMangleContext().mangleBlock(GD, BD, Buffer); 325 else 326 getCXXABI().getMangleContext().mangleName(ND, Buffer); 327 328 // Allocate space for the mangled name. 329 size_t Length = Buffer.size(); 330 char *Name = MangledNamesAllocator.Allocate<char>(Length); 331 std::copy(Buffer.begin(), Buffer.end(), Name); 332 333 Str = llvm::StringRef(Name, Length); 334 335 return Str; 336 } 337 338 void CodeGenModule::getMangledName(GlobalDecl GD, MangleBuffer &Buffer, 339 const BlockDecl *BD) { 340 getCXXABI().getMangleContext().mangleBlock(GD, BD, Buffer.getBuffer()); 341 } 342 343 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) { 344 return getModule().getNamedValue(Name); 345 } 346 347 /// AddGlobalCtor - Add a function to the list that will be called before 348 /// main() runs. 349 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 350 // FIXME: Type coercion of void()* types. 351 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 352 } 353 354 /// AddGlobalDtor - Add a function to the list that will be called 355 /// when the module is unloaded. 356 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 357 // FIXME: Type coercion of void()* types. 358 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 359 } 360 361 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 362 // Ctor function type is void()*. 363 llvm::FunctionType* CtorFTy = 364 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 365 std::vector<const llvm::Type*>(), 366 false); 367 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 368 369 // Get the type of a ctor entry, { i32, void ()* }. 370 llvm::StructType* CtorStructTy = 371 llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext), 372 llvm::PointerType::getUnqual(CtorFTy), NULL); 373 374 // Construct the constructor and destructor arrays. 375 std::vector<llvm::Constant*> Ctors; 376 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 377 std::vector<llvm::Constant*> S; 378 S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 379 I->second, false)); 380 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 381 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 382 } 383 384 if (!Ctors.empty()) { 385 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 386 new llvm::GlobalVariable(TheModule, AT, false, 387 llvm::GlobalValue::AppendingLinkage, 388 llvm::ConstantArray::get(AT, Ctors), 389 GlobalName); 390 } 391 } 392 393 void CodeGenModule::EmitAnnotations() { 394 if (Annotations.empty()) 395 return; 396 397 // Create a new global variable for the ConstantStruct in the Module. 398 llvm::Constant *Array = 399 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 400 Annotations.size()), 401 Annotations); 402 llvm::GlobalValue *gv = 403 new llvm::GlobalVariable(TheModule, Array->getType(), false, 404 llvm::GlobalValue::AppendingLinkage, Array, 405 "llvm.global.annotations"); 406 gv->setSection("llvm.metadata"); 407 } 408 409 llvm::GlobalValue::LinkageTypes 410 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) { 411 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 412 413 if (Linkage == GVA_Internal) 414 return llvm::Function::InternalLinkage; 415 416 if (D->hasAttr<DLLExportAttr>()) 417 return llvm::Function::DLLExportLinkage; 418 419 if (D->hasAttr<WeakAttr>()) 420 return llvm::Function::WeakAnyLinkage; 421 422 // In C99 mode, 'inline' functions are guaranteed to have a strong 423 // definition somewhere else, so we can use available_externally linkage. 424 if (Linkage == GVA_C99Inline) 425 return llvm::Function::AvailableExternallyLinkage; 426 427 // In C++, the compiler has to emit a definition in every translation unit 428 // that references the function. We should use linkonce_odr because 429 // a) if all references in this translation unit are optimized away, we 430 // don't need to codegen it. b) if the function persists, it needs to be 431 // merged with other definitions. c) C++ has the ODR, so we know the 432 // definition is dependable. 433 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 434 return llvm::Function::LinkOnceODRLinkage; 435 436 // An explicit instantiation of a template has weak linkage, since 437 // explicit instantiations can occur in multiple translation units 438 // and must all be equivalent. However, we are not allowed to 439 // throw away these explicit instantiations. 440 if (Linkage == GVA_ExplicitTemplateInstantiation) 441 return llvm::Function::WeakODRLinkage; 442 443 // Otherwise, we have strong external linkage. 444 assert(Linkage == GVA_StrongExternal); 445 return llvm::Function::ExternalLinkage; 446 } 447 448 449 /// SetFunctionDefinitionAttributes - Set attributes for a global. 450 /// 451 /// FIXME: This is currently only done for aliases and functions, but not for 452 /// variables (these details are set in EmitGlobalVarDefinition for variables). 453 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D, 454 llvm::GlobalValue *GV) { 455 SetCommonAttributes(D, GV); 456 } 457 458 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D, 459 const CGFunctionInfo &Info, 460 llvm::Function *F) { 461 unsigned CallingConv; 462 AttributeListType AttributeList; 463 ConstructAttributeList(Info, D, AttributeList, CallingConv); 464 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 465 AttributeList.size())); 466 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 467 } 468 469 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 470 llvm::Function *F) { 471 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 472 F->addFnAttr(llvm::Attribute::NoUnwind); 473 474 if (D->hasAttr<AlwaysInlineAttr>()) 475 F->addFnAttr(llvm::Attribute::AlwaysInline); 476 477 if (D->hasAttr<NakedAttr>()) 478 F->addFnAttr(llvm::Attribute::Naked); 479 480 if (D->hasAttr<NoInlineAttr>()) 481 F->addFnAttr(llvm::Attribute::NoInline); 482 483 if (Features.getStackProtectorMode() == LangOptions::SSPOn) 484 F->addFnAttr(llvm::Attribute::StackProtect); 485 else if (Features.getStackProtectorMode() == LangOptions::SSPReq) 486 F->addFnAttr(llvm::Attribute::StackProtectReq); 487 488 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 489 if (alignment) 490 F->setAlignment(alignment); 491 492 // C++ ABI requires 2-byte alignment for member functions. 493 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 494 F->setAlignment(2); 495 } 496 497 void CodeGenModule::SetCommonAttributes(const Decl *D, 498 llvm::GlobalValue *GV) { 499 setGlobalVisibility(GV, D); 500 501 if (D->hasAttr<UsedAttr>()) 502 AddUsedGlobal(GV); 503 504 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 505 GV->setSection(SA->getName()); 506 507 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this); 508 } 509 510 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D, 511 llvm::Function *F, 512 const CGFunctionInfo &FI) { 513 SetLLVMFunctionAttributes(D, FI, F); 514 SetLLVMFunctionAttributesForDefinition(D, F); 515 516 F->setLinkage(llvm::Function::InternalLinkage); 517 518 SetCommonAttributes(D, F); 519 } 520 521 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 522 llvm::Function *F, 523 bool IsIncompleteFunction) { 524 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 525 526 if (!IsIncompleteFunction) 527 SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F); 528 529 // Only a few attributes are set on declarations; these may later be 530 // overridden by a definition. 531 532 if (FD->hasAttr<DLLImportAttr>()) { 533 F->setLinkage(llvm::Function::DLLImportLinkage); 534 } else if (FD->hasAttr<WeakAttr>() || 535 FD->hasAttr<WeakImportAttr>()) { 536 // "extern_weak" is overloaded in LLVM; we probably should have 537 // separate linkage types for this. 538 F->setLinkage(llvm::Function::ExternalWeakLinkage); 539 } else { 540 F->setLinkage(llvm::Function::ExternalLinkage); 541 } 542 543 if (const SectionAttr *SA = FD->getAttr<SectionAttr>()) 544 F->setSection(SA->getName()); 545 } 546 547 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 548 assert(!GV->isDeclaration() && 549 "Only globals with definition can force usage."); 550 LLVMUsed.push_back(GV); 551 } 552 553 void CodeGenModule::EmitLLVMUsed() { 554 // Don't create llvm.used if there is no need. 555 if (LLVMUsed.empty()) 556 return; 557 558 const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext); 559 560 // Convert LLVMUsed to what ConstantArray needs. 561 std::vector<llvm::Constant*> UsedArray; 562 UsedArray.resize(LLVMUsed.size()); 563 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) { 564 UsedArray[i] = 565 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]), 566 i8PTy); 567 } 568 569 if (UsedArray.empty()) 570 return; 571 llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size()); 572 573 llvm::GlobalVariable *GV = 574 new llvm::GlobalVariable(getModule(), ATy, false, 575 llvm::GlobalValue::AppendingLinkage, 576 llvm::ConstantArray::get(ATy, UsedArray), 577 "llvm.used"); 578 579 GV->setSection("llvm.metadata"); 580 } 581 582 void CodeGenModule::EmitDeferred() { 583 // Emit code for any potentially referenced deferred decls. Since a 584 // previously unused static decl may become used during the generation of code 585 // for a static function, iterate until no changes are made. 586 587 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) { 588 if (!DeferredVTables.empty()) { 589 const CXXRecordDecl *RD = DeferredVTables.back(); 590 DeferredVTables.pop_back(); 591 getVTables().GenerateClassData(getVTableLinkage(RD), RD); 592 continue; 593 } 594 595 GlobalDecl D = DeferredDeclsToEmit.back(); 596 DeferredDeclsToEmit.pop_back(); 597 598 // Check to see if we've already emitted this. This is necessary 599 // for a couple of reasons: first, decls can end up in the 600 // deferred-decls queue multiple times, and second, decls can end 601 // up with definitions in unusual ways (e.g. by an extern inline 602 // function acquiring a strong function redefinition). Just 603 // ignore these cases. 604 // 605 // TODO: That said, looking this up multiple times is very wasteful. 606 llvm::StringRef Name = getMangledName(D); 607 llvm::GlobalValue *CGRef = GetGlobalValue(Name); 608 assert(CGRef && "Deferred decl wasn't referenced?"); 609 610 if (!CGRef->isDeclaration()) 611 continue; 612 613 // GlobalAlias::isDeclaration() defers to the aliasee, but for our 614 // purposes an alias counts as a definition. 615 if (isa<llvm::GlobalAlias>(CGRef)) 616 continue; 617 618 // Otherwise, emit the definition and move on to the next one. 619 EmitGlobalDefinition(D); 620 } 621 } 622 623 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 624 /// annotation information for a given GlobalValue. The annotation struct is 625 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 626 /// GlobalValue being annotated. The second field is the constant string 627 /// created from the AnnotateAttr's annotation. The third field is a constant 628 /// string containing the name of the translation unit. The fourth field is 629 /// the line number in the file of the annotated value declaration. 630 /// 631 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 632 /// appears to. 633 /// 634 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 635 const AnnotateAttr *AA, 636 unsigned LineNo) { 637 llvm::Module *M = &getModule(); 638 639 // get [N x i8] constants for the annotation string, and the filename string 640 // which are the 2nd and 3rd elements of the global annotation structure. 641 const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext); 642 llvm::Constant *anno = llvm::ConstantArray::get(VMContext, 643 AA->getAnnotation(), true); 644 llvm::Constant *unit = llvm::ConstantArray::get(VMContext, 645 M->getModuleIdentifier(), 646 true); 647 648 // Get the two global values corresponding to the ConstantArrays we just 649 // created to hold the bytes of the strings. 650 llvm::GlobalValue *annoGV = 651 new llvm::GlobalVariable(*M, anno->getType(), false, 652 llvm::GlobalValue::PrivateLinkage, anno, 653 GV->getName()); 654 // translation unit name string, emitted into the llvm.metadata section. 655 llvm::GlobalValue *unitGV = 656 new llvm::GlobalVariable(*M, unit->getType(), false, 657 llvm::GlobalValue::PrivateLinkage, unit, 658 ".str"); 659 660 // Create the ConstantStruct for the global annotation. 661 llvm::Constant *Fields[4] = { 662 llvm::ConstantExpr::getBitCast(GV, SBP), 663 llvm::ConstantExpr::getBitCast(annoGV, SBP), 664 llvm::ConstantExpr::getBitCast(unitGV, SBP), 665 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo) 666 }; 667 return llvm::ConstantStruct::get(VMContext, Fields, 4, false); 668 } 669 670 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 671 // Never defer when EmitAllDecls is specified. 672 if (Features.EmitAllDecls) 673 return false; 674 675 return !getContext().DeclMustBeEmitted(Global); 676 } 677 678 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 679 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 680 assert(AA && "No alias?"); 681 682 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 683 684 // See if there is already something with the target's name in the module. 685 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 686 687 llvm::Constant *Aliasee; 688 if (isa<llvm::FunctionType>(DeclTy)) 689 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 690 else 691 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 692 llvm::PointerType::getUnqual(DeclTy), 0); 693 if (!Entry) { 694 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee); 695 F->setLinkage(llvm::Function::ExternalWeakLinkage); 696 WeakRefReferences.insert(F); 697 } 698 699 return Aliasee; 700 } 701 702 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 703 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl()); 704 705 // Weak references don't produce any output by themselves. 706 if (Global->hasAttr<WeakRefAttr>()) 707 return; 708 709 // If this is an alias definition (which otherwise looks like a declaration) 710 // emit it now. 711 if (Global->hasAttr<AliasAttr>()) 712 return EmitAliasDefinition(GD); 713 714 // Ignore declarations, they will be emitted on their first use. 715 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 716 if (FD->getIdentifier()) { 717 llvm::StringRef Name = FD->getName(); 718 if (Name == "_Block_object_assign") { 719 BlockObjectAssignDecl = FD; 720 } else if (Name == "_Block_object_dispose") { 721 BlockObjectDisposeDecl = FD; 722 } 723 } 724 725 // Forward declarations are emitted lazily on first use. 726 if (!FD->isThisDeclarationADefinition()) 727 return; 728 } else { 729 const VarDecl *VD = cast<VarDecl>(Global); 730 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 731 732 if (VD->getIdentifier()) { 733 llvm::StringRef Name = VD->getName(); 734 if (Name == "_NSConcreteGlobalBlock") { 735 NSConcreteGlobalBlockDecl = VD; 736 } else if (Name == "_NSConcreteStackBlock") { 737 NSConcreteStackBlockDecl = VD; 738 } 739 } 740 741 742 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) 743 return; 744 } 745 746 // Defer code generation when possible if this is a static definition, inline 747 // function etc. These we only want to emit if they are used. 748 if (!MayDeferGeneration(Global)) { 749 // Emit the definition if it can't be deferred. 750 EmitGlobalDefinition(GD); 751 return; 752 } 753 754 // If we're deferring emission of a C++ variable with an 755 // initializer, remember the order in which it appeared in the file. 756 if (getLangOptions().CPlusPlus && isa<VarDecl>(Global) && 757 cast<VarDecl>(Global)->hasInit()) { 758 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 759 CXXGlobalInits.push_back(0); 760 } 761 762 // If the value has already been used, add it directly to the 763 // DeferredDeclsToEmit list. 764 llvm::StringRef MangledName = getMangledName(GD); 765 if (GetGlobalValue(MangledName)) 766 DeferredDeclsToEmit.push_back(GD); 767 else { 768 // Otherwise, remember that we saw a deferred decl with this name. The 769 // first use of the mangled name will cause it to move into 770 // DeferredDeclsToEmit. 771 DeferredDecls[MangledName] = GD; 772 } 773 } 774 775 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) { 776 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 777 778 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 779 Context.getSourceManager(), 780 "Generating code for declaration"); 781 782 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 783 // At -O0, don't generate IR for functions with available_externally 784 // linkage. 785 if (CodeGenOpts.OptimizationLevel == 0 && 786 !Function->hasAttr<AlwaysInlineAttr>() && 787 getFunctionLinkage(Function) 788 == llvm::Function::AvailableExternallyLinkage) 789 return; 790 791 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 792 if (Method->isVirtual()) 793 getVTables().EmitThunks(GD); 794 795 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method)) 796 return EmitCXXConstructor(CD, GD.getCtorType()); 797 798 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(Method)) 799 return EmitCXXDestructor(DD, GD.getDtorType()); 800 } 801 802 return EmitGlobalFunctionDefinition(GD); 803 } 804 805 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 806 return EmitGlobalVarDefinition(VD); 807 808 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 809 } 810 811 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 812 /// module, create and return an llvm Function with the specified type. If there 813 /// is something in the module with the specified name, return it potentially 814 /// bitcasted to the right type. 815 /// 816 /// If D is non-null, it specifies a decl that correspond to this. This is used 817 /// to set the attributes on the function when it is first created. 818 llvm::Constant * 819 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName, 820 const llvm::Type *Ty, 821 GlobalDecl D) { 822 // Lookup the entry, lazily creating it if necessary. 823 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 824 if (Entry) { 825 if (WeakRefReferences.count(Entry)) { 826 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl()); 827 if (FD && !FD->hasAttr<WeakAttr>()) 828 Entry->setLinkage(llvm::Function::ExternalLinkage); 829 830 WeakRefReferences.erase(Entry); 831 } 832 833 if (Entry->getType()->getElementType() == Ty) 834 return Entry; 835 836 // Make sure the result is of the correct type. 837 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 838 return llvm::ConstantExpr::getBitCast(Entry, PTy); 839 } 840 841 // This function doesn't have a complete type (for example, the return 842 // type is an incomplete struct). Use a fake type instead, and make 843 // sure not to try to set attributes. 844 bool IsIncompleteFunction = false; 845 846 const llvm::FunctionType *FTy; 847 if (isa<llvm::FunctionType>(Ty)) { 848 FTy = cast<llvm::FunctionType>(Ty); 849 } else { 850 FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 851 std::vector<const llvm::Type*>(), false); 852 IsIncompleteFunction = true; 853 } 854 855 llvm::Function *F = llvm::Function::Create(FTy, 856 llvm::Function::ExternalLinkage, 857 MangledName, &getModule()); 858 assert(F->getName() == MangledName && "name was uniqued!"); 859 if (D.getDecl()) 860 SetFunctionAttributes(D, F, IsIncompleteFunction); 861 862 // This is the first use or definition of a mangled name. If there is a 863 // deferred decl with this name, remember that we need to emit it at the end 864 // of the file. 865 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 866 if (DDI != DeferredDecls.end()) { 867 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 868 // list, and remove it from DeferredDecls (since we don't need it anymore). 869 DeferredDeclsToEmit.push_back(DDI->second); 870 DeferredDecls.erase(DDI); 871 } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) { 872 // If this the first reference to a C++ inline function in a class, queue up 873 // the deferred function body for emission. These are not seen as 874 // top-level declarations. 875 if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD)) 876 DeferredDeclsToEmit.push_back(D); 877 // A called constructor which has no definition or declaration need be 878 // synthesized. 879 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) { 880 if (CD->isImplicit()) { 881 assert(CD->isUsed() && "Sema doesn't consider constructor as used."); 882 DeferredDeclsToEmit.push_back(D); 883 } 884 } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) { 885 if (DD->isImplicit()) { 886 assert(DD->isUsed() && "Sema doesn't consider destructor as used."); 887 DeferredDeclsToEmit.push_back(D); 888 } 889 } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 890 if (MD->isImplicit() && MD->isCopyAssignmentOperator()) { 891 assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used."); 892 DeferredDeclsToEmit.push_back(D); 893 } 894 } 895 } 896 897 // Make sure the result is of the requested type. 898 if (!IsIncompleteFunction) { 899 assert(F->getType()->getElementType() == Ty); 900 return F; 901 } 902 903 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 904 return llvm::ConstantExpr::getBitCast(F, PTy); 905 } 906 907 /// GetAddrOfFunction - Return the address of the given function. If Ty is 908 /// non-null, then this function will use the specified type if it has to 909 /// create it (this occurs when we see a definition of the function). 910 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 911 const llvm::Type *Ty) { 912 // If there was no specific requested type, just convert it now. 913 if (!Ty) 914 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType()); 915 916 llvm::StringRef MangledName = getMangledName(GD); 917 return GetOrCreateLLVMFunction(MangledName, Ty, GD); 918 } 919 920 /// CreateRuntimeFunction - Create a new runtime function with the specified 921 /// type and name. 922 llvm::Constant * 923 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 924 llvm::StringRef Name) { 925 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl()); 926 } 927 928 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) { 929 if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType()) 930 return false; 931 if (Context.getLangOptions().CPlusPlus && 932 Context.getBaseElementType(D->getType())->getAs<RecordType>()) { 933 // FIXME: We should do something fancier here! 934 return false; 935 } 936 return true; 937 } 938 939 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 940 /// create and return an llvm GlobalVariable with the specified type. If there 941 /// is something in the module with the specified name, return it potentially 942 /// bitcasted to the right type. 943 /// 944 /// If D is non-null, it specifies a decl that correspond to this. This is used 945 /// to set the attributes on the global when it is first created. 946 llvm::Constant * 947 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName, 948 const llvm::PointerType *Ty, 949 const VarDecl *D) { 950 // Lookup the entry, lazily creating it if necessary. 951 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 952 if (Entry) { 953 if (WeakRefReferences.count(Entry)) { 954 if (D && !D->hasAttr<WeakAttr>()) 955 Entry->setLinkage(llvm::Function::ExternalLinkage); 956 957 WeakRefReferences.erase(Entry); 958 } 959 960 if (Entry->getType() == Ty) 961 return Entry; 962 963 // Make sure the result is of the correct type. 964 return llvm::ConstantExpr::getBitCast(Entry, Ty); 965 } 966 967 // This is the first use or definition of a mangled name. If there is a 968 // deferred decl with this name, remember that we need to emit it at the end 969 // of the file. 970 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName); 971 if (DDI != DeferredDecls.end()) { 972 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 973 // list, and remove it from DeferredDecls (since we don't need it anymore). 974 DeferredDeclsToEmit.push_back(DDI->second); 975 DeferredDecls.erase(DDI); 976 } 977 978 llvm::GlobalVariable *GV = 979 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false, 980 llvm::GlobalValue::ExternalLinkage, 981 0, MangledName, 0, 982 false, Ty->getAddressSpace()); 983 984 // Handle things which are present even on external declarations. 985 if (D) { 986 // FIXME: This code is overly simple and should be merged with other global 987 // handling. 988 GV->setConstant(DeclIsConstantGlobal(Context, D)); 989 990 // FIXME: Merge with other attribute handling code. 991 if (D->getStorageClass() == SC_PrivateExtern) 992 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 993 994 if (D->hasAttr<DLLImportAttr>()) 995 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage); 996 else if (D->hasAttr<WeakAttr>() || 997 D->hasAttr<WeakImportAttr>()) 998 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 999 1000 GV->setThreadLocal(D->isThreadSpecified()); 1001 } 1002 1003 return GV; 1004 } 1005 1006 1007 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 1008 /// given global variable. If Ty is non-null and if the global doesn't exist, 1009 /// then it will be greated with the specified type instead of whatever the 1010 /// normal requested type would be. 1011 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 1012 const llvm::Type *Ty) { 1013 assert(D->hasGlobalStorage() && "Not a global variable"); 1014 QualType ASTTy = D->getType(); 1015 if (Ty == 0) 1016 Ty = getTypes().ConvertTypeForMem(ASTTy); 1017 1018 const llvm::PointerType *PTy = 1019 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 1020 1021 llvm::StringRef MangledName = getMangledName(D); 1022 return GetOrCreateLLVMGlobal(MangledName, PTy, D); 1023 } 1024 1025 /// CreateRuntimeVariable - Create a new runtime global variable with the 1026 /// specified type and name. 1027 llvm::Constant * 1028 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 1029 llvm::StringRef Name) { 1030 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 1031 } 1032 1033 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 1034 assert(!D->getInit() && "Cannot emit definite definitions here!"); 1035 1036 if (MayDeferGeneration(D)) { 1037 // If we have not seen a reference to this variable yet, place it 1038 // into the deferred declarations table to be emitted if needed 1039 // later. 1040 llvm::StringRef MangledName = getMangledName(D); 1041 if (!GetGlobalValue(MangledName)) { 1042 DeferredDecls[MangledName] = D; 1043 return; 1044 } 1045 } 1046 1047 // The tentative definition is the only definition. 1048 EmitGlobalVarDefinition(D); 1049 } 1050 1051 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) { 1052 if (DefinitionRequired) 1053 getVTables().GenerateClassData(getVTableLinkage(Class), Class); 1054 } 1055 1056 llvm::GlobalVariable::LinkageTypes 1057 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) { 1058 if (RD->isInAnonymousNamespace() || !RD->hasLinkage()) 1059 return llvm::GlobalVariable::InternalLinkage; 1060 1061 if (const CXXMethodDecl *KeyFunction 1062 = RD->getASTContext().getKeyFunction(RD)) { 1063 // If this class has a key function, use that to determine the linkage of 1064 // the vtable. 1065 const FunctionDecl *Def = 0; 1066 if (KeyFunction->hasBody(Def)) 1067 KeyFunction = cast<CXXMethodDecl>(Def); 1068 1069 switch (KeyFunction->getTemplateSpecializationKind()) { 1070 case TSK_Undeclared: 1071 case TSK_ExplicitSpecialization: 1072 if (KeyFunction->isInlined()) 1073 return llvm::GlobalVariable::WeakODRLinkage; 1074 1075 return llvm::GlobalVariable::ExternalLinkage; 1076 1077 case TSK_ImplicitInstantiation: 1078 case TSK_ExplicitInstantiationDefinition: 1079 return llvm::GlobalVariable::WeakODRLinkage; 1080 1081 case TSK_ExplicitInstantiationDeclaration: 1082 // FIXME: Use available_externally linkage. However, this currently 1083 // breaks LLVM's build due to undefined symbols. 1084 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1085 return llvm::GlobalVariable::WeakODRLinkage; 1086 } 1087 } 1088 1089 switch (RD->getTemplateSpecializationKind()) { 1090 case TSK_Undeclared: 1091 case TSK_ExplicitSpecialization: 1092 case TSK_ImplicitInstantiation: 1093 case TSK_ExplicitInstantiationDefinition: 1094 return llvm::GlobalVariable::WeakODRLinkage; 1095 1096 case TSK_ExplicitInstantiationDeclaration: 1097 // FIXME: Use available_externally linkage. However, this currently 1098 // breaks LLVM's build due to undefined symbols. 1099 // return llvm::GlobalVariable::AvailableExternallyLinkage; 1100 return llvm::GlobalVariable::WeakODRLinkage; 1101 } 1102 1103 // Silence GCC warning. 1104 return llvm::GlobalVariable::WeakODRLinkage; 1105 } 1106 1107 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const { 1108 return CharUnits::fromQuantity( 1109 TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth()); 1110 } 1111 1112 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 1113 llvm::Constant *Init = 0; 1114 QualType ASTTy = D->getType(); 1115 bool NonConstInit = false; 1116 1117 const Expr *InitExpr = D->getAnyInitializer(); 1118 1119 if (!InitExpr) { 1120 // This is a tentative definition; tentative definitions are 1121 // implicitly initialized with { 0 }. 1122 // 1123 // Note that tentative definitions are only emitted at the end of 1124 // a translation unit, so they should never have incomplete 1125 // type. In addition, EmitTentativeDefinition makes sure that we 1126 // never attempt to emit a tentative definition if a real one 1127 // exists. A use may still exists, however, so we still may need 1128 // to do a RAUW. 1129 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 1130 Init = EmitNullConstant(D->getType()); 1131 } else { 1132 Init = EmitConstantExpr(InitExpr, D->getType()); 1133 if (!Init) { 1134 QualType T = InitExpr->getType(); 1135 if (D->getType()->isReferenceType()) 1136 T = D->getType(); 1137 1138 if (getLangOptions().CPlusPlus) { 1139 EmitCXXGlobalVarDeclInitFunc(D); 1140 Init = EmitNullConstant(T); 1141 NonConstInit = true; 1142 } else { 1143 ErrorUnsupported(D, "static initializer"); 1144 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 1145 } 1146 } else { 1147 // We don't need an initializer, so remove the entry for the delayed 1148 // initializer position (just in case this entry was delayed). 1149 if (getLangOptions().CPlusPlus) 1150 DelayedCXXInitPosition.erase(D); 1151 } 1152 } 1153 1154 const llvm::Type* InitType = Init->getType(); 1155 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 1156 1157 // Strip off a bitcast if we got one back. 1158 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1159 assert(CE->getOpcode() == llvm::Instruction::BitCast || 1160 // all zero index gep. 1161 CE->getOpcode() == llvm::Instruction::GetElementPtr); 1162 Entry = CE->getOperand(0); 1163 } 1164 1165 // Entry is now either a Function or GlobalVariable. 1166 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 1167 1168 // We have a definition after a declaration with the wrong type. 1169 // We must make a new GlobalVariable* and update everything that used OldGV 1170 // (a declaration or tentative definition) with the new GlobalVariable* 1171 // (which will be a definition). 1172 // 1173 // This happens if there is a prototype for a global (e.g. 1174 // "extern int x[];") and then a definition of a different type (e.g. 1175 // "int x[10];"). This also happens when an initializer has a different type 1176 // from the type of the global (this happens with unions). 1177 if (GV == 0 || 1178 GV->getType()->getElementType() != InitType || 1179 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 1180 1181 // Move the old entry aside so that we'll create a new one. 1182 Entry->setName(llvm::StringRef()); 1183 1184 // Make a new global with the correct type, this is now guaranteed to work. 1185 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 1186 1187 // Replace all uses of the old global with the new global 1188 llvm::Constant *NewPtrForOldDecl = 1189 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 1190 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1191 1192 // Erase the old global, since it is no longer used. 1193 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 1194 } 1195 1196 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 1197 SourceManager &SM = Context.getSourceManager(); 1198 AddAnnotation(EmitAnnotateAttr(GV, AA, 1199 SM.getInstantiationLineNumber(D->getLocation()))); 1200 } 1201 1202 GV->setInitializer(Init); 1203 1204 // If it is safe to mark the global 'constant', do so now. 1205 GV->setConstant(false); 1206 if (!NonConstInit && DeclIsConstantGlobal(Context, D)) 1207 GV->setConstant(true); 1208 1209 GV->setAlignment(getContext().getDeclAlign(D).getQuantity()); 1210 1211 // Set the llvm linkage type as appropriate. 1212 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D); 1213 if (Linkage == GVA_Internal) 1214 GV->setLinkage(llvm::Function::InternalLinkage); 1215 else if (D->hasAttr<DLLImportAttr>()) 1216 GV->setLinkage(llvm::Function::DLLImportLinkage); 1217 else if (D->hasAttr<DLLExportAttr>()) 1218 GV->setLinkage(llvm::Function::DLLExportLinkage); 1219 else if (D->hasAttr<WeakAttr>()) { 1220 if (GV->isConstant()) 1221 GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage); 1222 else 1223 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1224 } else if (Linkage == GVA_TemplateInstantiation || 1225 Linkage == GVA_ExplicitTemplateInstantiation) 1226 // FIXME: It seems like we can provide more specific linkage here 1227 // (LinkOnceODR, WeakODR). 1228 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 1229 else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon && 1230 !D->hasExternalStorage() && !D->getInit() && 1231 !D->getAttr<SectionAttr>() && !D->isThreadSpecified()) { 1232 // Thread local vars aren't considered common linkage. 1233 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 1234 // common vars aren't constant even if declared const. 1235 GV->setConstant(false); 1236 } else 1237 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 1238 1239 SetCommonAttributes(D, GV); 1240 1241 // Emit global variable debug information. 1242 if (CGDebugInfo *DI = getDebugInfo()) { 1243 DI->setLocation(D->getLocation()); 1244 DI->EmitGlobalVariable(GV, D); 1245 } 1246 } 1247 1248 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 1249 /// implement a function with no prototype, e.g. "int foo() {}". If there are 1250 /// existing call uses of the old function in the module, this adjusts them to 1251 /// call the new function directly. 1252 /// 1253 /// This is not just a cleanup: the always_inline pass requires direct calls to 1254 /// functions to be able to inline them. If there is a bitcast in the way, it 1255 /// won't inline them. Instcombine normally deletes these calls, but it isn't 1256 /// run at -O0. 1257 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 1258 llvm::Function *NewFn) { 1259 // If we're redefining a global as a function, don't transform it. 1260 llvm::Function *OldFn = dyn_cast<llvm::Function>(Old); 1261 if (OldFn == 0) return; 1262 1263 const llvm::Type *NewRetTy = NewFn->getReturnType(); 1264 llvm::SmallVector<llvm::Value*, 4> ArgList; 1265 1266 for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end(); 1267 UI != E; ) { 1268 // TODO: Do invokes ever occur in C code? If so, we should handle them too. 1269 llvm::Value::use_iterator I = UI++; // Increment before the CI is erased. 1270 llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I); 1271 if (!CI) continue; // FIXME: when we allow Invoke, just do CallSite CS(*I) 1272 llvm::CallSite CS(CI); 1273 if (!CI || !CS.isCallee(I)) continue; 1274 1275 // If the return types don't match exactly, and if the call isn't dead, then 1276 // we can't transform this call. 1277 if (CI->getType() != NewRetTy && !CI->use_empty()) 1278 continue; 1279 1280 // If the function was passed too few arguments, don't transform. If extra 1281 // arguments were passed, we silently drop them. If any of the types 1282 // mismatch, we don't transform. 1283 unsigned ArgNo = 0; 1284 bool DontTransform = false; 1285 for (llvm::Function::arg_iterator AI = NewFn->arg_begin(), 1286 E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) { 1287 if (CS.arg_size() == ArgNo || 1288 CS.getArgument(ArgNo)->getType() != AI->getType()) { 1289 DontTransform = true; 1290 break; 1291 } 1292 } 1293 if (DontTransform) 1294 continue; 1295 1296 // Okay, we can transform this. Create the new call instruction and copy 1297 // over the required information. 1298 ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo); 1299 llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(), 1300 ArgList.end(), "", CI); 1301 ArgList.clear(); 1302 if (!NewCall->getType()->isVoidTy()) 1303 NewCall->takeName(CI); 1304 NewCall->setAttributes(CI->getAttributes()); 1305 NewCall->setCallingConv(CI->getCallingConv()); 1306 1307 // Finally, remove the old call, replacing any uses with the new one. 1308 if (!CI->use_empty()) 1309 CI->replaceAllUsesWith(NewCall); 1310 1311 // Copy debug location attached to CI. 1312 if (!CI->getDebugLoc().isUnknown()) 1313 NewCall->setDebugLoc(CI->getDebugLoc()); 1314 CI->eraseFromParent(); 1315 } 1316 } 1317 1318 1319 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) { 1320 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl()); 1321 const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD); 1322 getCXXABI().getMangleContext().mangleInitDiscriminator(); 1323 // Get or create the prototype for the function. 1324 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty); 1325 1326 // Strip off a bitcast if we got one back. 1327 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 1328 assert(CE->getOpcode() == llvm::Instruction::BitCast); 1329 Entry = CE->getOperand(0); 1330 } 1331 1332 1333 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 1334 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry); 1335 1336 // If the types mismatch then we have to rewrite the definition. 1337 assert(OldFn->isDeclaration() && 1338 "Shouldn't replace non-declaration"); 1339 1340 // F is the Function* for the one with the wrong type, we must make a new 1341 // Function* and update everything that used F (a declaration) with the new 1342 // Function* (which will be a definition). 1343 // 1344 // This happens if there is a prototype for a function 1345 // (e.g. "int f()") and then a definition of a different type 1346 // (e.g. "int f(int x)"). Move the old function aside so that it 1347 // doesn't interfere with GetAddrOfFunction. 1348 OldFn->setName(llvm::StringRef()); 1349 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty)); 1350 1351 // If this is an implementation of a function without a prototype, try to 1352 // replace any existing uses of the function (which may be calls) with uses 1353 // of the new function 1354 if (D->getType()->isFunctionNoProtoType()) { 1355 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn); 1356 OldFn->removeDeadConstantUsers(); 1357 } 1358 1359 // Replace uses of F with the Function we will endow with a body. 1360 if (!Entry->use_empty()) { 1361 llvm::Constant *NewPtrForOldDecl = 1362 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 1363 Entry->replaceAllUsesWith(NewPtrForOldDecl); 1364 } 1365 1366 // Ok, delete the old function now, which is dead. 1367 OldFn->eraseFromParent(); 1368 1369 Entry = NewFn; 1370 } 1371 1372 llvm::Function *Fn = cast<llvm::Function>(Entry); 1373 setFunctionLinkage(D, Fn); 1374 1375 CodeGenFunction(*this).GenerateCode(D, Fn); 1376 1377 SetFunctionDefinitionAttributes(D, Fn); 1378 SetLLVMFunctionAttributesForDefinition(D, Fn); 1379 1380 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 1381 AddGlobalCtor(Fn, CA->getPriority()); 1382 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 1383 AddGlobalDtor(Fn, DA->getPriority()); 1384 } 1385 1386 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 1387 const ValueDecl *D = cast<ValueDecl>(GD.getDecl()); 1388 const AliasAttr *AA = D->getAttr<AliasAttr>(); 1389 assert(AA && "Not an alias?"); 1390 1391 llvm::StringRef MangledName = getMangledName(GD); 1392 1393 // If there is a definition in the module, then it wins over the alias. 1394 // This is dubious, but allow it to be safe. Just ignore the alias. 1395 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 1396 if (Entry && !Entry->isDeclaration()) 1397 return; 1398 1399 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 1400 1401 // Create a reference to the named value. This ensures that it is emitted 1402 // if a deferred decl. 1403 llvm::Constant *Aliasee; 1404 if (isa<llvm::FunctionType>(DeclTy)) 1405 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl()); 1406 else 1407 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 1408 llvm::PointerType::getUnqual(DeclTy), 0); 1409 1410 // Create the new alias itself, but don't set a name yet. 1411 llvm::GlobalValue *GA = 1412 new llvm::GlobalAlias(Aliasee->getType(), 1413 llvm::Function::ExternalLinkage, 1414 "", Aliasee, &getModule()); 1415 1416 if (Entry) { 1417 assert(Entry->isDeclaration()); 1418 1419 // If there is a declaration in the module, then we had an extern followed 1420 // by the alias, as in: 1421 // extern int test6(); 1422 // ... 1423 // int test6() __attribute__((alias("test7"))); 1424 // 1425 // Remove it and replace uses of it with the alias. 1426 GA->takeName(Entry); 1427 1428 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 1429 Entry->getType())); 1430 Entry->eraseFromParent(); 1431 } else { 1432 GA->setName(MangledName); 1433 } 1434 1435 // Set attributes which are particular to an alias; this is a 1436 // specialization of the attributes which may be set on a global 1437 // variable/function. 1438 if (D->hasAttr<DLLExportAttr>()) { 1439 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1440 // The dllexport attribute is ignored for undefined symbols. 1441 if (FD->hasBody()) 1442 GA->setLinkage(llvm::Function::DLLExportLinkage); 1443 } else { 1444 GA->setLinkage(llvm::Function::DLLExportLinkage); 1445 } 1446 } else if (D->hasAttr<WeakAttr>() || 1447 D->hasAttr<WeakRefAttr>() || 1448 D->hasAttr<WeakImportAttr>()) { 1449 GA->setLinkage(llvm::Function::WeakAnyLinkage); 1450 } 1451 1452 SetCommonAttributes(D, GA); 1453 } 1454 1455 /// getBuiltinLibFunction - Given a builtin id for a function like 1456 /// "__builtin_fabsf", return a Function* for "fabsf". 1457 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD, 1458 unsigned BuiltinID) { 1459 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 1460 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 1461 "isn't a lib fn"); 1462 1463 // Get the name, skip over the __builtin_ prefix (if necessary). 1464 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 1465 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 1466 Name += 10; 1467 1468 const llvm::FunctionType *Ty = 1469 cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType())); 1470 1471 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD)); 1472 } 1473 1474 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 1475 unsigned NumTys) { 1476 return llvm::Intrinsic::getDeclaration(&getModule(), 1477 (llvm::Intrinsic::ID)IID, Tys, NumTys); 1478 } 1479 1480 1481 llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType, 1482 const llvm::Type *SrcType, 1483 const llvm::Type *SizeType) { 1484 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1485 return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3); 1486 } 1487 1488 llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType, 1489 const llvm::Type *SrcType, 1490 const llvm::Type *SizeType) { 1491 const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType }; 1492 return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3); 1493 } 1494 1495 llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType, 1496 const llvm::Type *SizeType) { 1497 const llvm::Type *ArgTypes[2] = { DestType, SizeType }; 1498 return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2); 1499 } 1500 1501 static llvm::StringMapEntry<llvm::Constant*> & 1502 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map, 1503 const StringLiteral *Literal, 1504 bool TargetIsLSB, 1505 bool &IsUTF16, 1506 unsigned &StringLength) { 1507 llvm::StringRef String = Literal->getString(); 1508 unsigned NumBytes = String.size(); 1509 1510 // Check for simple case. 1511 if (!Literal->containsNonAsciiOrNull()) { 1512 StringLength = NumBytes; 1513 return Map.GetOrCreateValue(String); 1514 } 1515 1516 // Otherwise, convert the UTF8 literals into a byte string. 1517 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes); 1518 const UTF8 *FromPtr = (UTF8 *)String.data(); 1519 UTF16 *ToPtr = &ToBuf[0]; 1520 1521 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, 1522 &ToPtr, ToPtr + NumBytes, 1523 strictConversion); 1524 1525 // ConvertUTF8toUTF16 returns the length in ToPtr. 1526 StringLength = ToPtr - &ToBuf[0]; 1527 1528 // Render the UTF-16 string into a byte array and convert to the target byte 1529 // order. 1530 // 1531 // FIXME: This isn't something we should need to do here. 1532 llvm::SmallString<128> AsBytes; 1533 AsBytes.reserve(StringLength * 2); 1534 for (unsigned i = 0; i != StringLength; ++i) { 1535 unsigned short Val = ToBuf[i]; 1536 if (TargetIsLSB) { 1537 AsBytes.push_back(Val & 0xFF); 1538 AsBytes.push_back(Val >> 8); 1539 } else { 1540 AsBytes.push_back(Val >> 8); 1541 AsBytes.push_back(Val & 0xFF); 1542 } 1543 } 1544 // Append one extra null character, the second is automatically added by our 1545 // caller. 1546 AsBytes.push_back(0); 1547 1548 IsUTF16 = true; 1549 return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size())); 1550 } 1551 1552 llvm::Constant * 1553 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 1554 unsigned StringLength = 0; 1555 bool isUTF16 = false; 1556 llvm::StringMapEntry<llvm::Constant*> &Entry = 1557 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1558 getTargetData().isLittleEndian(), 1559 isUTF16, StringLength); 1560 1561 if (llvm::Constant *C = Entry.getValue()) 1562 return C; 1563 1564 llvm::Constant *Zero = 1565 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1566 llvm::Constant *Zeros[] = { Zero, Zero }; 1567 1568 // If we don't already have it, get __CFConstantStringClassReference. 1569 if (!CFConstantStringClassRef) { 1570 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1571 Ty = llvm::ArrayType::get(Ty, 0); 1572 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1573 "__CFConstantStringClassReference"); 1574 // Decay array -> ptr 1575 CFConstantStringClassRef = 1576 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1577 } 1578 1579 QualType CFTy = getContext().getCFConstantStringType(); 1580 1581 const llvm::StructType *STy = 1582 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1583 1584 std::vector<llvm::Constant*> Fields(4); 1585 1586 // Class pointer. 1587 Fields[0] = CFConstantStringClassRef; 1588 1589 // Flags. 1590 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1591 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) : 1592 llvm::ConstantInt::get(Ty, 0x07C8); 1593 1594 // String pointer. 1595 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1596 1597 llvm::GlobalValue::LinkageTypes Linkage; 1598 bool isConstant; 1599 if (isUTF16) { 1600 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1601 Linkage = llvm::GlobalValue::InternalLinkage; 1602 // Note: -fwritable-strings doesn't make unicode CFStrings writable, but 1603 // does make plain ascii ones writable. 1604 isConstant = true; 1605 } else { 1606 Linkage = llvm::GlobalValue::PrivateLinkage; 1607 isConstant = !Features.WritableStrings; 1608 } 1609 1610 llvm::GlobalVariable *GV = 1611 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1612 ".str"); 1613 if (isUTF16) { 1614 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1615 GV->setAlignment(Align.getQuantity()); 1616 } 1617 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1618 1619 // String length. 1620 Ty = getTypes().ConvertType(getContext().LongTy); 1621 Fields[3] = llvm::ConstantInt::get(Ty, StringLength); 1622 1623 // The struct. 1624 C = llvm::ConstantStruct::get(STy, Fields); 1625 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1626 llvm::GlobalVariable::PrivateLinkage, C, 1627 "_unnamed_cfstring_"); 1628 if (const char *Sect = getContext().Target.getCFStringSection()) 1629 GV->setSection(Sect); 1630 Entry.setValue(GV); 1631 1632 return GV; 1633 } 1634 1635 llvm::Constant * 1636 CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) { 1637 unsigned StringLength = 0; 1638 bool isUTF16 = false; 1639 llvm::StringMapEntry<llvm::Constant*> &Entry = 1640 GetConstantCFStringEntry(CFConstantStringMap, Literal, 1641 getTargetData().isLittleEndian(), 1642 isUTF16, StringLength); 1643 1644 if (llvm::Constant *C = Entry.getValue()) 1645 return C; 1646 1647 llvm::Constant *Zero = 1648 llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext)); 1649 llvm::Constant *Zeros[] = { Zero, Zero }; 1650 1651 // If we don't already have it, get _NSConstantStringClassReference. 1652 if (!NSConstantStringClassRef) { 1653 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1654 Ty = llvm::ArrayType::get(Ty, 0); 1655 llvm::Constant *GV = CreateRuntimeVariable(Ty, 1656 Features.ObjCNonFragileABI ? 1657 "OBJC_CLASS_$_NSConstantString" : 1658 "_NSConstantStringClassReference"); 1659 // Decay array -> ptr 1660 NSConstantStringClassRef = 1661 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1662 } 1663 1664 QualType NSTy = getContext().getNSConstantStringType(); 1665 1666 const llvm::StructType *STy = 1667 cast<llvm::StructType>(getTypes().ConvertType(NSTy)); 1668 1669 std::vector<llvm::Constant*> Fields(3); 1670 1671 // Class pointer. 1672 Fields[0] = NSConstantStringClassRef; 1673 1674 // String pointer. 1675 llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str()); 1676 1677 llvm::GlobalValue::LinkageTypes Linkage; 1678 bool isConstant; 1679 if (isUTF16) { 1680 // FIXME: why do utf strings get "_" labels instead of "L" labels? 1681 Linkage = llvm::GlobalValue::InternalLinkage; 1682 // Note: -fwritable-strings doesn't make unicode NSStrings writable, but 1683 // does make plain ascii ones writable. 1684 isConstant = true; 1685 } else { 1686 Linkage = llvm::GlobalValue::PrivateLinkage; 1687 isConstant = !Features.WritableStrings; 1688 } 1689 1690 llvm::GlobalVariable *GV = 1691 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C, 1692 ".str"); 1693 if (isUTF16) { 1694 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy); 1695 GV->setAlignment(Align.getQuantity()); 1696 } 1697 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1698 1699 // String length. 1700 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1701 Fields[2] = llvm::ConstantInt::get(Ty, StringLength); 1702 1703 // The struct. 1704 C = llvm::ConstantStruct::get(STy, Fields); 1705 GV = new llvm::GlobalVariable(getModule(), C->getType(), true, 1706 llvm::GlobalVariable::PrivateLinkage, C, 1707 "_unnamed_nsstring_"); 1708 // FIXME. Fix section. 1709 if (const char *Sect = 1710 Features.ObjCNonFragileABI 1711 ? getContext().Target.getNSStringNonFragileABISection() 1712 : getContext().Target.getNSStringSection()) 1713 GV->setSection(Sect); 1714 Entry.setValue(GV); 1715 1716 return GV; 1717 } 1718 1719 /// GetStringForStringLiteral - Return the appropriate bytes for a 1720 /// string literal, properly padded to match the literal type. 1721 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1722 const ConstantArrayType *CAT = 1723 getContext().getAsConstantArrayType(E->getType()); 1724 assert(CAT && "String isn't pointer or array!"); 1725 1726 // Resize the string to the right size. 1727 uint64_t RealLen = CAT->getSize().getZExtValue(); 1728 1729 if (E->isWide()) 1730 RealLen *= getContext().Target.getWCharWidth()/8; 1731 1732 std::string Str = E->getString().str(); 1733 Str.resize(RealLen, '\0'); 1734 1735 return Str; 1736 } 1737 1738 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1739 /// constant array for the given string literal. 1740 llvm::Constant * 1741 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1742 // FIXME: This can be more efficient. 1743 // FIXME: We shouldn't need to bitcast the constant in the wide string case. 1744 llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S)); 1745 if (S->isWide()) { 1746 llvm::Type *DestTy = 1747 llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType())); 1748 C = llvm::ConstantExpr::getBitCast(C, DestTy); 1749 } 1750 return C; 1751 } 1752 1753 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1754 /// array for the given ObjCEncodeExpr node. 1755 llvm::Constant * 1756 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1757 std::string Str; 1758 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1759 1760 return GetAddrOfConstantCString(Str); 1761 } 1762 1763 1764 /// GenerateWritableString -- Creates storage for a string literal. 1765 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1766 bool constant, 1767 CodeGenModule &CGM, 1768 const char *GlobalName) { 1769 // Create Constant for this string literal. Don't add a '\0'. 1770 llvm::Constant *C = 1771 llvm::ConstantArray::get(CGM.getLLVMContext(), str, false); 1772 1773 // Create a global variable for this string 1774 return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant, 1775 llvm::GlobalValue::PrivateLinkage, 1776 C, GlobalName); 1777 } 1778 1779 /// GetAddrOfConstantString - Returns a pointer to a character array 1780 /// containing the literal. This contents are exactly that of the 1781 /// given string, i.e. it will not be null terminated automatically; 1782 /// see GetAddrOfConstantCString. Note that whether the result is 1783 /// actually a pointer to an LLVM constant depends on 1784 /// Feature.WriteableStrings. 1785 /// 1786 /// The result has pointer to array type. 1787 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1788 const char *GlobalName) { 1789 bool IsConstant = !Features.WritableStrings; 1790 1791 // Get the default prefix if a name wasn't specified. 1792 if (!GlobalName) 1793 GlobalName = ".str"; 1794 1795 // Don't share any string literals if strings aren't constant. 1796 if (!IsConstant) 1797 return GenerateStringLiteral(str, false, *this, GlobalName); 1798 1799 llvm::StringMapEntry<llvm::Constant *> &Entry = 1800 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1801 1802 if (Entry.getValue()) 1803 return Entry.getValue(); 1804 1805 // Create a global variable for this. 1806 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1807 Entry.setValue(C); 1808 return C; 1809 } 1810 1811 /// GetAddrOfConstantCString - Returns a pointer to a character 1812 /// array containing the literal and a terminating '\-' 1813 /// character. The result has pointer to array type. 1814 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1815 const char *GlobalName){ 1816 return GetAddrOfConstantString(str + '\0', GlobalName); 1817 } 1818 1819 /// EmitObjCPropertyImplementations - Emit information for synthesized 1820 /// properties for an implementation. 1821 void CodeGenModule::EmitObjCPropertyImplementations(const 1822 ObjCImplementationDecl *D) { 1823 for (ObjCImplementationDecl::propimpl_iterator 1824 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) { 1825 ObjCPropertyImplDecl *PID = *i; 1826 1827 // Dynamic is just for type-checking. 1828 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1829 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1830 1831 // Determine which methods need to be implemented, some may have 1832 // been overridden. Note that ::isSynthesized is not the method 1833 // we want, that just indicates if the decl came from a 1834 // property. What we want to know is if the method is defined in 1835 // this implementation. 1836 if (!D->getInstanceMethod(PD->getGetterName())) 1837 CodeGenFunction(*this).GenerateObjCGetter( 1838 const_cast<ObjCImplementationDecl *>(D), PID); 1839 if (!PD->isReadOnly() && 1840 !D->getInstanceMethod(PD->getSetterName())) 1841 CodeGenFunction(*this).GenerateObjCSetter( 1842 const_cast<ObjCImplementationDecl *>(D), PID); 1843 } 1844 } 1845 } 1846 1847 /// EmitObjCIvarInitializations - Emit information for ivar initialization 1848 /// for an implementation. 1849 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 1850 if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0) 1851 return; 1852 DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D)); 1853 assert(DC && "EmitObjCIvarInitializations - null DeclContext"); 1854 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 1855 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 1856 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(), 1857 D->getLocation(), 1858 D->getLocation(), cxxSelector, 1859 getContext().VoidTy, 0, 1860 DC, true, false, true, false, 1861 ObjCMethodDecl::Required); 1862 D->addInstanceMethod(DTORMethod); 1863 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 1864 1865 II = &getContext().Idents.get(".cxx_construct"); 1866 cxxSelector = getContext().Selectors.getSelector(0, &II); 1867 // The constructor returns 'self'. 1868 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(), 1869 D->getLocation(), 1870 D->getLocation(), cxxSelector, 1871 getContext().getObjCIdType(), 0, 1872 DC, true, false, true, false, 1873 ObjCMethodDecl::Required); 1874 D->addInstanceMethod(CTORMethod); 1875 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 1876 1877 1878 } 1879 1880 /// EmitNamespace - Emit all declarations in a namespace. 1881 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) { 1882 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end(); 1883 I != E; ++I) 1884 EmitTopLevelDecl(*I); 1885 } 1886 1887 // EmitLinkageSpec - Emit all declarations in a linkage spec. 1888 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 1889 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 1890 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 1891 ErrorUnsupported(LSD, "linkage spec"); 1892 return; 1893 } 1894 1895 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end(); 1896 I != E; ++I) 1897 EmitTopLevelDecl(*I); 1898 } 1899 1900 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1901 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1902 // If an error has occurred, stop code generation, but continue 1903 // parsing and semantic analysis (to ensure all warnings and errors 1904 // are emitted). 1905 if (Diags.hasErrorOccurred()) 1906 return; 1907 1908 // Ignore dependent declarations. 1909 if (D->getDeclContext() && D->getDeclContext()->isDependentContext()) 1910 return; 1911 1912 switch (D->getKind()) { 1913 case Decl::CXXConversion: 1914 case Decl::CXXMethod: 1915 case Decl::Function: 1916 // Skip function templates 1917 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1918 return; 1919 1920 EmitGlobal(cast<FunctionDecl>(D)); 1921 break; 1922 1923 case Decl::Var: 1924 EmitGlobal(cast<VarDecl>(D)); 1925 break; 1926 1927 // C++ Decls 1928 case Decl::Namespace: 1929 EmitNamespace(cast<NamespaceDecl>(D)); 1930 break; 1931 // No code generation needed. 1932 case Decl::UsingShadow: 1933 case Decl::Using: 1934 case Decl::UsingDirective: 1935 case Decl::ClassTemplate: 1936 case Decl::FunctionTemplate: 1937 case Decl::NamespaceAlias: 1938 break; 1939 case Decl::CXXConstructor: 1940 // Skip function templates 1941 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate()) 1942 return; 1943 1944 EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 1945 break; 1946 case Decl::CXXDestructor: 1947 EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 1948 break; 1949 1950 case Decl::StaticAssert: 1951 // Nothing to do. 1952 break; 1953 1954 // Objective-C Decls 1955 1956 // Forward declarations, no (immediate) code generation. 1957 case Decl::ObjCClass: 1958 case Decl::ObjCForwardProtocol: 1959 case Decl::ObjCInterface: 1960 break; 1961 1962 case Decl::ObjCCategory: { 1963 ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D); 1964 if (CD->IsClassExtension() && CD->hasSynthBitfield()) 1965 Context.ResetObjCLayout(CD->getClassInterface()); 1966 break; 1967 } 1968 1969 1970 case Decl::ObjCProtocol: 1971 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1972 break; 1973 1974 case Decl::ObjCCategoryImpl: 1975 // Categories have properties but don't support synthesize so we 1976 // can ignore them here. 1977 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1978 break; 1979 1980 case Decl::ObjCImplementation: { 1981 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1982 if (Features.ObjCNonFragileABI2 && OMD->hasSynthBitfield()) 1983 Context.ResetObjCLayout(OMD->getClassInterface()); 1984 EmitObjCPropertyImplementations(OMD); 1985 EmitObjCIvarInitializations(OMD); 1986 Runtime->GenerateClass(OMD); 1987 break; 1988 } 1989 case Decl::ObjCMethod: { 1990 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1991 // If this is not a prototype, emit the body. 1992 if (OMD->getBody()) 1993 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1994 break; 1995 } 1996 case Decl::ObjCCompatibleAlias: 1997 // compatibility-alias is a directive and has no code gen. 1998 break; 1999 2000 case Decl::LinkageSpec: 2001 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 2002 break; 2003 2004 case Decl::FileScopeAsm: { 2005 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 2006 llvm::StringRef AsmString = AD->getAsmString()->getString(); 2007 2008 const std::string &S = getModule().getModuleInlineAsm(); 2009 if (S.empty()) 2010 getModule().setModuleInlineAsm(AsmString); 2011 else 2012 getModule().setModuleInlineAsm(S + '\n' + AsmString.str()); 2013 break; 2014 } 2015 2016 default: 2017 // Make sure we handled everything we should, every other kind is a 2018 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 2019 // function. Need to recode Decl::Kind to do that easily. 2020 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 2021 } 2022 } 2023 2024 /// Turns the given pointer into a constant. 2025 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 2026 const void *Ptr) { 2027 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 2028 const llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 2029 return llvm::ConstantInt::get(i64, PtrInt); 2030 } 2031 2032 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 2033 llvm::NamedMDNode *&GlobalMetadata, 2034 GlobalDecl D, 2035 llvm::GlobalValue *Addr) { 2036 if (!GlobalMetadata) 2037 GlobalMetadata = 2038 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 2039 2040 // TODO: should we report variant information for ctors/dtors? 2041 llvm::Value *Ops[] = { 2042 Addr, 2043 GetPointerConstant(CGM.getLLVMContext(), D.getDecl()) 2044 }; 2045 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops, 2)); 2046 } 2047 2048 /// Emits metadata nodes associating all the global values in the 2049 /// current module with the Decls they came from. This is useful for 2050 /// projects using IR gen as a subroutine. 2051 /// 2052 /// Since there's currently no way to associate an MDNode directly 2053 /// with an llvm::GlobalValue, we create a global named metadata 2054 /// with the name 'clang.global.decl.ptrs'. 2055 void CodeGenModule::EmitDeclMetadata() { 2056 llvm::NamedMDNode *GlobalMetadata = 0; 2057 2058 // StaticLocalDeclMap 2059 for (llvm::DenseMap<GlobalDecl,llvm::StringRef>::iterator 2060 I = MangledDeclNames.begin(), E = MangledDeclNames.end(); 2061 I != E; ++I) { 2062 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second); 2063 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr); 2064 } 2065 } 2066 2067 /// Emits metadata nodes for all the local variables in the current 2068 /// function. 2069 void CodeGenFunction::EmitDeclMetadata() { 2070 if (LocalDeclMap.empty()) return; 2071 2072 llvm::LLVMContext &Context = getLLVMContext(); 2073 2074 // Find the unique metadata ID for this name. 2075 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 2076 2077 llvm::NamedMDNode *GlobalMetadata = 0; 2078 2079 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator 2080 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) { 2081 const Decl *D = I->first; 2082 llvm::Value *Addr = I->second; 2083 2084 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 2085 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 2086 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, &DAddr, 1)); 2087 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 2088 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 2089 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 2090 } 2091 } 2092 } 2093 2094 ///@name Custom Runtime Function Interfaces 2095 ///@{ 2096 // 2097 // FIXME: These can be eliminated once we can have clients just get the required 2098 // AST nodes from the builtin tables. 2099 2100 llvm::Constant *CodeGenModule::getBlockObjectDispose() { 2101 if (BlockObjectDispose) 2102 return BlockObjectDispose; 2103 2104 // If we saw an explicit decl, use that. 2105 if (BlockObjectDisposeDecl) { 2106 return BlockObjectDispose = GetAddrOfFunction( 2107 BlockObjectDisposeDecl, 2108 getTypes().GetFunctionType(BlockObjectDisposeDecl)); 2109 } 2110 2111 // Otherwise construct the function by hand. 2112 const llvm::FunctionType *FTy; 2113 std::vector<const llvm::Type*> ArgTys; 2114 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext); 2115 ArgTys.push_back(PtrToInt8Ty); 2116 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext)); 2117 FTy = llvm::FunctionType::get(ResultType, ArgTys, false); 2118 return BlockObjectDispose = 2119 CreateRuntimeFunction(FTy, "_Block_object_dispose"); 2120 } 2121 2122 llvm::Constant *CodeGenModule::getBlockObjectAssign() { 2123 if (BlockObjectAssign) 2124 return BlockObjectAssign; 2125 2126 // If we saw an explicit decl, use that. 2127 if (BlockObjectAssignDecl) { 2128 return BlockObjectAssign = GetAddrOfFunction( 2129 BlockObjectAssignDecl, 2130 getTypes().GetFunctionType(BlockObjectAssignDecl)); 2131 } 2132 2133 // Otherwise construct the function by hand. 2134 const llvm::FunctionType *FTy; 2135 std::vector<const llvm::Type*> ArgTys; 2136 const llvm::Type *ResultType = llvm::Type::getVoidTy(VMContext); 2137 ArgTys.push_back(PtrToInt8Ty); 2138 ArgTys.push_back(PtrToInt8Ty); 2139 ArgTys.push_back(llvm::Type::getInt32Ty(VMContext)); 2140 FTy = llvm::FunctionType::get(ResultType, ArgTys, false); 2141 return BlockObjectAssign = 2142 CreateRuntimeFunction(FTy, "_Block_object_assign"); 2143 } 2144 2145 llvm::Constant *CodeGenModule::getNSConcreteGlobalBlock() { 2146 if (NSConcreteGlobalBlock) 2147 return NSConcreteGlobalBlock; 2148 2149 // If we saw an explicit decl, use that. 2150 if (NSConcreteGlobalBlockDecl) { 2151 return NSConcreteGlobalBlock = GetAddrOfGlobalVar( 2152 NSConcreteGlobalBlockDecl, 2153 getTypes().ConvertType(NSConcreteGlobalBlockDecl->getType())); 2154 } 2155 2156 // Otherwise construct the variable by hand. 2157 return NSConcreteGlobalBlock = CreateRuntimeVariable( 2158 PtrToInt8Ty, "_NSConcreteGlobalBlock"); 2159 } 2160 2161 llvm::Constant *CodeGenModule::getNSConcreteStackBlock() { 2162 if (NSConcreteStackBlock) 2163 return NSConcreteStackBlock; 2164 2165 // If we saw an explicit decl, use that. 2166 if (NSConcreteStackBlockDecl) { 2167 return NSConcreteStackBlock = GetAddrOfGlobalVar( 2168 NSConcreteStackBlockDecl, 2169 getTypes().ConvertType(NSConcreteStackBlockDecl->getType())); 2170 } 2171 2172 // Otherwise construct the variable by hand. 2173 return NSConcreteStackBlock = CreateRuntimeVariable( 2174 PtrToInt8Ty, "_NSConcreteStackBlock"); 2175 } 2176 2177 ///@} 2178