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