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