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