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 "CGDebugInfo.h" 15 #include "CodeGenModule.h" 16 #include "CodeGenFunction.h" 17 #include "CGCall.h" 18 #include "CGObjCRuntime.h" 19 #include "Mangle.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/Basic/Diagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "llvm/CallingConv.h" 27 #include "llvm/Module.h" 28 #include "llvm/Intrinsics.h" 29 #include "llvm/Target/TargetData.h" 30 using namespace clang; 31 using namespace CodeGen; 32 33 34 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 35 llvm::Module &M, const llvm::TargetData &TD, 36 Diagnostic &diags, bool GenerateDebugInfo) 37 : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M), 38 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0), 39 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) { 40 41 if (!Features.ObjC1) 42 Runtime = 0; 43 else if (!Features.NeXTRuntime) 44 Runtime = CreateGNUObjCRuntime(*this); 45 else if (Features.ObjCNonFragileABI) 46 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 47 else 48 Runtime = CreateMacObjCRuntime(*this); 49 50 // If debug info generation is enabled, create the CGDebugInfo object. 51 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0; 52 } 53 54 CodeGenModule::~CodeGenModule() { 55 delete Runtime; 56 delete DebugInfo; 57 } 58 59 void CodeGenModule::Release() { 60 EmitAliases(); 61 EmitDeferred(); 62 if (Runtime) 63 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 64 AddGlobalCtor(ObjCInitFunction); 65 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 66 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 67 EmitAnnotations(); 68 EmitLLVMUsed(); 69 } 70 71 /// ErrorUnsupported - Print out an error that codegen doesn't support the 72 /// specified stmt yet. 73 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 74 bool OmitOnError) { 75 if (OmitOnError && getDiags().hasErrorOccurred()) 76 return; 77 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 78 "cannot compile this %0 yet"); 79 std::string Msg = Type; 80 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 81 << Msg << S->getSourceRange(); 82 } 83 84 /// ErrorUnsupported - Print out an error that codegen doesn't support the 85 /// specified decl yet. 86 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 87 bool OmitOnError) { 88 if (OmitOnError && getDiags().hasErrorOccurred()) 89 return; 90 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 91 "cannot compile this %0 yet"); 92 std::string Msg = Type; 93 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 94 } 95 96 /// setGlobalVisibility - Set the visibility for the given LLVM 97 /// GlobalValue according to the given clang AST visibility value. 98 static void setGlobalVisibility(llvm::GlobalValue *GV, 99 VisibilityAttr::VisibilityTypes Vis) { 100 switch (Vis) { 101 default: assert(0 && "Unknown visibility!"); 102 case VisibilityAttr::DefaultVisibility: 103 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 104 break; 105 case VisibilityAttr::HiddenVisibility: 106 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 107 break; 108 case VisibilityAttr::ProtectedVisibility: 109 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 110 break; 111 } 112 } 113 114 /// \brief Retrieves the mangled name for the given declaration. 115 /// 116 /// If the given declaration requires a mangled name, returns an 117 /// const char* containing the mangled name. Otherwise, returns 118 /// the unmangled name. 119 /// 120 /// FIXME: Returning an IdentifierInfo* here is a total hack. We 121 /// really need some kind of string abstraction that either stores a 122 /// mangled name or stores an IdentifierInfo*. This will require 123 /// changes to the GlobalDeclMap, too. (I disagree, I think what we 124 /// actually need is for Sema to provide some notion of which Decls 125 /// refer to the same semantic decl. We shouldn't need to mangle the 126 /// names and see what comes out the same to figure this out. - DWD) 127 /// 128 /// FIXME: Performance here is going to be terribly until we start 129 /// caching mangled names. However, we should fix the problem above 130 /// first. 131 const char *CodeGenModule::getMangledName(const NamedDecl *ND) { 132 // In C, functions with no attributes never need to be mangled. Fastpath them. 133 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) { 134 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 135 return ND->getNameAsCString(); 136 } 137 138 llvm::SmallString<256> Name; 139 llvm::raw_svector_ostream Out(Name); 140 if (!mangleName(ND, Context, Out)) { 141 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 142 return ND->getNameAsCString(); 143 } 144 145 Name += '\0'; 146 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData(); 147 } 148 149 /// AddGlobalCtor - Add a function to the list that will be called before 150 /// main() runs. 151 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 152 // FIXME: Type coercion of void()* types. 153 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 154 } 155 156 /// AddGlobalDtor - Add a function to the list that will be called 157 /// when the module is unloaded. 158 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 159 // FIXME: Type coercion of void()* types. 160 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 161 } 162 163 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 164 // Ctor function type is void()*. 165 llvm::FunctionType* CtorFTy = 166 llvm::FunctionType::get(llvm::Type::VoidTy, 167 std::vector<const llvm::Type*>(), 168 false); 169 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 170 171 // Get the type of a ctor entry, { i32, void ()* }. 172 llvm::StructType* CtorStructTy = 173 llvm::StructType::get(llvm::Type::Int32Ty, 174 llvm::PointerType::getUnqual(CtorFTy), NULL); 175 176 // Construct the constructor and destructor arrays. 177 std::vector<llvm::Constant*> Ctors; 178 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 179 std::vector<llvm::Constant*> S; 180 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false)); 181 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 182 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 183 } 184 185 if (!Ctors.empty()) { 186 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 187 new llvm::GlobalVariable(AT, false, 188 llvm::GlobalValue::AppendingLinkage, 189 llvm::ConstantArray::get(AT, Ctors), 190 GlobalName, 191 &TheModule); 192 } 193 } 194 195 void CodeGenModule::EmitAnnotations() { 196 if (Annotations.empty()) 197 return; 198 199 // Create a new global variable for the ConstantStruct in the Module. 200 llvm::Constant *Array = 201 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 202 Annotations.size()), 203 Annotations); 204 llvm::GlobalValue *gv = 205 new llvm::GlobalVariable(Array->getType(), false, 206 llvm::GlobalValue::AppendingLinkage, Array, 207 "llvm.global.annotations", &TheModule); 208 gv->setSection("llvm.metadata"); 209 } 210 211 void CodeGenModule::SetGlobalValueAttributes(const Decl *D, 212 bool IsInternal, 213 bool IsInline, 214 llvm::GlobalValue *GV, 215 bool ForDefinition) { 216 // FIXME: Set up linkage and many other things. Note, this is a simple 217 // approximation of what we really want. 218 if (!ForDefinition) { 219 // Only a few attributes are set on declarations. 220 if (D->getAttr<DLLImportAttr>()) { 221 // The dllimport attribute is overridden by a subsequent declaration as 222 // dllexport. 223 if (!D->getAttr<DLLExportAttr>()) { 224 // dllimport attribute can be applied only to function decls, not to 225 // definitions. 226 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 227 if (!FD->getBody()) 228 GV->setLinkage(llvm::Function::DLLImportLinkage); 229 } else 230 GV->setLinkage(llvm::Function::DLLImportLinkage); 231 } 232 } else if (D->getAttr<WeakAttr>() || 233 D->getAttr<WeakImportAttr>()) { 234 // "extern_weak" is overloaded in LLVM; we probably should have 235 // separate linkage types for this. 236 GV->setLinkage(llvm::Function::ExternalWeakLinkage); 237 } 238 } else { 239 if (IsInternal) { 240 GV->setLinkage(llvm::Function::InternalLinkage); 241 } else { 242 if (D->getAttr<DLLExportAttr>()) { 243 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 244 // The dllexport attribute is ignored for undefined symbols. 245 if (FD->getBody()) 246 GV->setLinkage(llvm::Function::DLLExportLinkage); 247 } else 248 GV->setLinkage(llvm::Function::DLLExportLinkage); 249 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() || 250 IsInline) 251 GV->setLinkage(llvm::Function::WeakAnyLinkage); 252 } 253 } 254 255 // FIXME: Figure out the relative priority of the attribute, 256 // -fvisibility, and private_extern. 257 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 258 setGlobalVisibility(GV, attr->getVisibility()); 259 // FIXME: else handle -fvisibility 260 261 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 262 GV->setSection(SA->getName()); 263 264 // Only add to llvm.used when we see a definition, otherwise we 265 // might add multiple times or risk the value being replaced by a 266 // subsequent RAUW. 267 if (ForDefinition) { 268 if (D->getAttr<UsedAttr>()) 269 AddUsedGlobal(GV); 270 } 271 } 272 273 void CodeGenModule::SetFunctionAttributes(const Decl *D, 274 const CGFunctionInfo &Info, 275 llvm::Function *F) { 276 AttributeListType AttributeList; 277 ConstructAttributeList(Info, D, AttributeList); 278 279 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 280 AttributeList.size())); 281 282 // Set the appropriate calling convention for the Function. 283 if (D->getAttr<FastCallAttr>()) 284 F->setCallingConv(llvm::CallingConv::X86_FastCall); 285 286 if (D->getAttr<StdCallAttr>()) 287 F->setCallingConv(llvm::CallingConv::X86_StdCall); 288 } 289 290 /// SetFunctionAttributesForDefinition - Set function attributes 291 /// specific to a function definition. 292 void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D, 293 llvm::Function *F) { 294 if (isa<ObjCMethodDecl>(D)) { 295 SetGlobalValueAttributes(D, true, false, F, true); 296 } else { 297 const FunctionDecl *FD = cast<FunctionDecl>(D); 298 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static, 299 FD->isInline(), F, true); 300 } 301 302 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 303 F->addFnAttr(llvm::Attribute::NoUnwind); 304 305 if (D->getAttr<AlwaysInlineAttr>()) 306 F->addFnAttr(llvm::Attribute::AlwaysInline); 307 308 if (D->getAttr<NoinlineAttr>()) 309 F->addFnAttr(llvm::Attribute::NoInline); 310 } 311 312 void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD, 313 llvm::Function *F) { 314 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F); 315 316 SetFunctionAttributesForDefinition(MD, F); 317 } 318 319 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 320 llvm::Function *F) { 321 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); 322 323 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static, 324 FD->isInline(), F, false); 325 } 326 327 328 void CodeGenModule::EmitAliases() { 329 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) { 330 const ValueDecl *D = Aliases[i]; 331 const AliasAttr *AA = D->getAttr<AliasAttr>(); 332 333 // This is something of a hack, if the FunctionDecl got overridden 334 // then its attributes will be moved to the new declaration. In 335 // this case the current decl has no alias attribute, but we will 336 // eventually see it. 337 if (!AA) 338 continue; 339 340 const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 341 342 // Unique the name through the identifier table. 343 const char *AliaseeName = AA->getAliasee().c_str(); 344 AliaseeName = getContext().Idents.get(AliaseeName).getName(); 345 346 347 348 llvm::Constant *Aliasee; 349 if (isa<llvm::FunctionType>(DeclTy)) 350 Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, 0); 351 else 352 Aliasee = GetOrCreateLLVMGlobal(AliaseeName, 353 llvm::PointerType::getUnqual(DeclTy), 0); 354 355 const char *MangledName = getMangledName(D); 356 llvm::GlobalValue *GA = 357 new llvm::GlobalAlias(Aliasee->getType(), 358 llvm::Function::ExternalLinkage, 359 MangledName, Aliasee, &getModule()); 360 361 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 362 if (Entry) { 363 // If we created a dummy function for this then replace it. 364 GA->takeName(Entry); 365 366 llvm::Value *Casted = 367 llvm::ConstantExpr::getBitCast(GA, Entry->getType()); 368 Entry->replaceAllUsesWith(Casted); 369 Entry->eraseFromParent(); 370 371 Entry = GA; 372 } 373 374 // Alias should never be internal or inline. 375 SetGlobalValueAttributes(D, false, false, GA, true); 376 } 377 } 378 379 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 380 assert(!GV->isDeclaration() && 381 "Only globals with definition can force usage."); 382 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 383 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy)); 384 } 385 386 void CodeGenModule::EmitLLVMUsed() { 387 // Don't create llvm.used if there is no need. 388 if (LLVMUsed.empty()) 389 return; 390 391 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(), 392 LLVMUsed.size()); 393 llvm::GlobalVariable *GV = 394 new llvm::GlobalVariable(ATy, false, 395 llvm::GlobalValue::AppendingLinkage, 396 llvm::ConstantArray::get(ATy, LLVMUsed), 397 "llvm.used", &getModule()); 398 399 GV->setSection("llvm.metadata"); 400 } 401 402 void CodeGenModule::EmitDeferred() { 403 // Emit code for any potentially referenced deferred decls. Since a 404 // previously unused static decl may become used during the generation of code 405 // for a static function, iterate until no changes are made. 406 while (!DeferredDeclsToEmit.empty()) { 407 const ValueDecl *D = DeferredDeclsToEmit.back(); 408 DeferredDeclsToEmit.pop_back(); 409 410 // The mangled name for the decl must have been emitted in GlobalDeclMap. 411 // Look it up to see if it was defined with a stronger definition (e.g. an 412 // extern inline function with a strong function redefinition). If so, 413 // just ignore the deferred decl. 414 llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)]; 415 assert(CGRef && "Deferred decl wasn't referenced?"); 416 417 if (!CGRef->isDeclaration()) 418 continue; 419 420 // Otherwise, emit the definition and move on to the next one. 421 EmitGlobalDefinition(D); 422 } 423 } 424 425 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 426 /// annotation information for a given GlobalValue. The annotation struct is 427 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 428 /// GlobalValue being annotated. The second field is the constant string 429 /// created from the AnnotateAttr's annotation. The third field is a constant 430 /// string containing the name of the translation unit. The fourth field is 431 /// the line number in the file of the annotated value declaration. 432 /// 433 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 434 /// appears to. 435 /// 436 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 437 const AnnotateAttr *AA, 438 unsigned LineNo) { 439 llvm::Module *M = &getModule(); 440 441 // get [N x i8] constants for the annotation string, and the filename string 442 // which are the 2nd and 3rd elements of the global annotation structure. 443 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 444 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true); 445 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(), 446 true); 447 448 // Get the two global values corresponding to the ConstantArrays we just 449 // created to hold the bytes of the strings. 450 llvm::GlobalValue *annoGV = 451 new llvm::GlobalVariable(anno->getType(), false, 452 llvm::GlobalValue::InternalLinkage, anno, 453 GV->getName() + ".str", M); 454 // translation unit name string, emitted into the llvm.metadata section. 455 llvm::GlobalValue *unitGV = 456 new llvm::GlobalVariable(unit->getType(), false, 457 llvm::GlobalValue::InternalLinkage, unit, ".str", M); 458 459 // Create the ConstantStruct that is the global annotion. 460 llvm::Constant *Fields[4] = { 461 llvm::ConstantExpr::getBitCast(GV, SBP), 462 llvm::ConstantExpr::getBitCast(annoGV, SBP), 463 llvm::ConstantExpr::getBitCast(unitGV, SBP), 464 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo) 465 }; 466 return llvm::ConstantStruct::get(Fields, 4, false); 467 } 468 469 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 470 // Never defer when EmitAllDecls is specified or the decl has 471 // attribute used. 472 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>()) 473 return false; 474 475 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 476 // Constructors and destructors should never be deferred. 477 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>()) 478 return false; 479 480 // FIXME: What about inline, and/or extern inline? 481 if (FD->getStorageClass() != FunctionDecl::Static) 482 return false; 483 } else { 484 const VarDecl *VD = cast<VarDecl>(Global); 485 assert(VD->isFileVarDecl() && "Invalid decl"); 486 487 if (VD->getStorageClass() != VarDecl::Static) 488 return false; 489 } 490 491 return true; 492 } 493 494 void CodeGenModule::EmitGlobal(const ValueDecl *Global) { 495 // Aliases are deferred until code for everything else has been 496 // emitted. 497 if (Global->getAttr<AliasAttr>()) { 498 Aliases.push_back(Global); 499 return; 500 } 501 502 // Ignore declarations, they will be emitted on their first use. 503 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 504 // Forward declarations are emitted lazily on first use. 505 if (!FD->isThisDeclarationADefinition()) 506 return; 507 } else { 508 const VarDecl *VD = cast<VarDecl>(Global); 509 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 510 511 // Forward declarations are emitted lazily on first use. 512 if (!VD->getInit() && VD->hasExternalStorage()) 513 return; 514 } 515 516 // Defer code generation when possible if this is a static definition, inline 517 // function etc. These we only want to emit if they are used. 518 if (MayDeferGeneration(Global)) { 519 // If the value has already been used, add it directly to the 520 // DeferredDeclsToEmit list. 521 const char *MangledName = getMangledName(Global); 522 if (GlobalDeclMap.count(MangledName)) 523 DeferredDeclsToEmit.push_back(Global); 524 else { 525 // Otherwise, remember that we saw a deferred decl with this name. The 526 // first use of the mangled name will cause it to move into 527 // DeferredDeclsToEmit. 528 DeferredDecls[MangledName] = Global; 529 } 530 return; 531 } 532 533 // Otherwise emit the definition. 534 EmitGlobalDefinition(Global); 535 } 536 537 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) { 538 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 539 EmitGlobalFunctionDefinition(FD); 540 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 541 EmitGlobalVarDefinition(VD); 542 } else { 543 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 544 } 545 } 546 547 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 548 /// module, create and return an llvm Function with the specified type. If there 549 /// is something in the module with the specified name, return it potentially 550 /// bitcasted to the right type. 551 /// 552 /// If D is non-null, it specifies a decl that correspond to this. This is used 553 /// to set the attributes on the function when it is first created. 554 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName, 555 const llvm::Type *Ty, 556 const FunctionDecl *D) { 557 // Lookup the entry, lazily creating it if necessary. 558 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 559 if (Entry) { 560 if (Entry->getType()->getElementType() == Ty) 561 return Entry; 562 563 // Make sure the result is of the correct type. 564 const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 565 return llvm::ConstantExpr::getBitCast(Entry, PTy); 566 } 567 568 // This is the first use or definition of a mangled name. If there is a 569 // deferred decl with this name, remember that we need to emit it at the end 570 // of the file. 571 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI = 572 DeferredDecls.find(MangledName); 573 if (DDI != DeferredDecls.end()) { 574 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 575 // list, and remove it from DeferredDecls (since we don't need it anymore). 576 DeferredDeclsToEmit.push_back(DDI->second); 577 DeferredDecls.erase(DDI); 578 } 579 580 // This function doesn't have a complete type (for example, the return 581 // type is an incomplete struct). Use a fake type instead, and make 582 // sure not to try to set attributes. 583 bool ShouldSetAttributes = true; 584 if (!isa<llvm::FunctionType>(Ty)) { 585 Ty = llvm::FunctionType::get(llvm::Type::VoidTy, 586 std::vector<const llvm::Type*>(), false); 587 ShouldSetAttributes = false; 588 } 589 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 590 llvm::Function::ExternalLinkage, 591 "", &getModule()); 592 F->setName(MangledName); 593 if (D && ShouldSetAttributes) 594 SetFunctionAttributes(D, F); 595 Entry = F; 596 return F; 597 } 598 599 /// GetAddrOfFunction - Return the address of the given function. If Ty is 600 /// non-null, then this function will use the specified type if it has to 601 /// create it (this occurs when we see a definition of the function). 602 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D, 603 const llvm::Type *Ty) { 604 // If there was no specific requested type, just convert it now. 605 if (!Ty) 606 Ty = getTypes().ConvertType(D->getType()); 607 return GetOrCreateLLVMFunction(getMangledName(D), Ty, D); 608 } 609 610 /// CreateRuntimeFunction - Create a new runtime function with the specified 611 /// type and name. 612 llvm::Constant * 613 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 614 const char *Name) { 615 // Convert Name to be a uniqued string from the IdentifierInfo table. 616 Name = getContext().Idents.get(Name).getName(); 617 return GetOrCreateLLVMFunction(Name, FTy, 0); 618 } 619 620 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 621 /// create and return an llvm GlobalVariable with the specified type. If there 622 /// is something in the module with the specified name, return it potentially 623 /// bitcasted to the right type. 624 /// 625 /// If D is non-null, it specifies a decl that correspond to this. This is used 626 /// to set the attributes on the global when it is first created. 627 llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName, 628 const llvm::PointerType*Ty, 629 const VarDecl *D) { 630 // Lookup the entry, lazily creating it if necessary. 631 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 632 if (Entry) { 633 if (Entry->getType() == Ty) 634 return Entry; 635 636 // Make sure the result is of the correct type. 637 return llvm::ConstantExpr::getBitCast(Entry, Ty); 638 } 639 640 // This is the first use or definition of a mangled name. If there is a 641 // deferred decl with this name, remember that we need to emit it at the end 642 // of the file. 643 llvm::DenseMap<const char*, const ValueDecl*>::iterator DDI = 644 DeferredDecls.find(MangledName); 645 if (DDI != DeferredDecls.end()) { 646 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 647 // list, and remove it from DeferredDecls (since we don't need it anymore). 648 DeferredDeclsToEmit.push_back(DDI->second); 649 DeferredDecls.erase(DDI); 650 } 651 652 llvm::GlobalVariable *GV = 653 new llvm::GlobalVariable(Ty->getElementType(), false, 654 llvm::GlobalValue::ExternalLinkage, 655 0, "", &getModule(), 656 0, Ty->getAddressSpace()); 657 GV->setName(MangledName); 658 659 // Handle things which are present even on external declarations. 660 if (D) { 661 // FIXME: This code is overly simple and should be merged with 662 // other global handling. 663 GV->setConstant(D->getType().isConstant(Context)); 664 665 // FIXME: Merge with other attribute handling code. 666 if (D->getStorageClass() == VarDecl::PrivateExtern) 667 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility); 668 669 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>()) 670 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 671 } 672 673 return Entry = GV; 674 } 675 676 677 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 678 /// given global variable. If Ty is non-null and if the global doesn't exist, 679 /// then it will be greated with the specified type instead of whatever the 680 /// normal requested type would be. 681 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 682 const llvm::Type *Ty) { 683 assert(D->hasGlobalStorage() && "Not a global variable"); 684 QualType ASTTy = D->getType(); 685 if (Ty == 0) 686 Ty = getTypes().ConvertTypeForMem(ASTTy); 687 688 const llvm::PointerType *PTy = 689 llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 690 return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D); 691 } 692 693 /// CreateRuntimeVariable - Create a new runtime global variable with the 694 /// specified type and name. 695 llvm::Constant * 696 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 697 const char *Name) { 698 // Convert Name to be a uniqued string from the IdentifierInfo table. 699 Name = getContext().Idents.get(Name).getName(); 700 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0); 701 } 702 703 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 704 llvm::Constant *Init = 0; 705 QualType ASTTy = D->getType(); 706 707 if (D->getInit() == 0) { 708 // This is a tentative definition; tentative definitions are 709 // implicitly initialized with { 0 } 710 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy); 711 if (ASTTy->isIncompleteArrayType()) { 712 // An incomplete array is normally [ TYPE x 0 ], but we need 713 // to fix it to [ TYPE x 1 ]. 714 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy); 715 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1); 716 } 717 Init = llvm::Constant::getNullValue(InitTy); 718 } else { 719 Init = EmitConstantExpr(D->getInit()); 720 if (!Init) { 721 ErrorUnsupported(D, "static initializer"); 722 QualType T = D->getInit()->getType(); 723 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 724 } 725 } 726 727 const llvm::Type* InitType = Init->getType(); 728 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 729 730 // Strip off a bitcast if we got one back. 731 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 732 assert(CE->getOpcode() == llvm::Instruction::BitCast); 733 Entry = CE->getOperand(0); 734 } 735 736 // Entry is now either a Function or GlobalVariable. 737 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 738 739 // If we already have this global and it has an initializer, then 740 // we are in the rare situation where we emitted the defining 741 // declaration of the global and are now being asked to emit a 742 // definition which would be common. This occurs, for example, in 743 // the following situation because statics can be emitted out of 744 // order: 745 // 746 // static int x; 747 // static int *y = &x; 748 // static int x = 10; 749 // int **z = &y; 750 // 751 // Bail here so we don't blow away the definition. Note that if we 752 // can't distinguish here if we emitted a definition with a null 753 // initializer, but this case is safe. 754 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) { 755 assert(!D->getInit() && "Emitting multiple definitions of a decl!"); 756 return; 757 } 758 759 // We have a definition after a declaration with the wrong type. 760 // We must make a new GlobalVariable* and update everything that used OldGV 761 // (a declaration or tentative definition) with the new GlobalVariable* 762 // (which will be a definition). 763 // 764 // This happens if there is a prototype for a global (e.g. 765 // "extern int x[];") and then a definition of a different type (e.g. 766 // "int x[10];"). This also happens when an initializer has a different type 767 // from the type of the global (this happens with unions). 768 // 769 // FIXME: This also ends up happening if there's a definition followed by 770 // a tentative definition! (Although Sema rejects that construct 771 // at the moment.) 772 if (GV == 0 || 773 GV->getType()->getElementType() != InitType || 774 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 775 776 // Remove the old entry from GlobalDeclMap so that we'll create a new one. 777 GlobalDeclMap.erase(getMangledName(D)); 778 779 // Make a new global with the correct type, this is now guaranteed to work. 780 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 781 GV->takeName(cast<llvm::GlobalValue>(Entry)); 782 783 // Replace all uses of the old global with the new global 784 llvm::Constant *NewPtrForOldDecl = 785 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 786 Entry->replaceAllUsesWith(NewPtrForOldDecl); 787 788 // Erase the old global, since it is no longer used. 789 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed. 790 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 791 } 792 793 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 794 SourceManager &SM = Context.getSourceManager(); 795 AddAnnotation(EmitAnnotateAttr(GV, AA, 796 SM.getInstantiationLineNumber(D->getLocation()))); 797 } 798 799 GV->setInitializer(Init); 800 GV->setConstant(D->getType().isConstant(Context)); 801 GV->setAlignment(getContext().getDeclAlignInBytes(D)); 802 803 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 804 setGlobalVisibility(GV, attr->getVisibility()); 805 // FIXME: else handle -fvisibility 806 807 // Set the llvm linkage type as appropriate. 808 if (D->getStorageClass() == VarDecl::Static) 809 GV->setLinkage(llvm::Function::InternalLinkage); 810 else if (D->getAttr<DLLImportAttr>()) 811 GV->setLinkage(llvm::Function::DLLImportLinkage); 812 else if (D->getAttr<DLLExportAttr>()) 813 GV->setLinkage(llvm::Function::DLLExportLinkage); 814 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>()) 815 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 816 else { 817 // FIXME: This isn't right. This should handle common linkage and other 818 // stuff. 819 switch (D->getStorageClass()) { 820 case VarDecl::Static: assert(0 && "This case handled above"); 821 case VarDecl::Auto: 822 case VarDecl::Register: 823 assert(0 && "Can't have auto or register globals"); 824 case VarDecl::None: 825 if (!D->getInit()) 826 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 827 else 828 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 829 break; 830 case VarDecl::Extern: 831 // FIXME: common 832 break; 833 834 case VarDecl::PrivateExtern: 835 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 836 // FIXME: common 837 break; 838 } 839 } 840 841 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 842 GV->setSection(SA->getName()); 843 844 if (D->getAttr<UsedAttr>()) 845 AddUsedGlobal(GV); 846 847 // Emit global variable debug information. 848 if (CGDebugInfo *DI = getDebugInfo()) { 849 DI->setLocation(D->getLocation()); 850 DI->EmitGlobalVariable(GV, D); 851 } 852 } 853 854 855 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) { 856 const llvm::FunctionType *Ty = 857 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType())); 858 859 // As a special case, make sure that definitions of K&R function 860 // "type foo()" aren't declared as varargs (which forces the backend 861 // to do unnecessary work). 862 if (D->getType()->isFunctionNoProtoType()) { 863 assert(Ty->isVarArg() && "Didn't lower type as expected"); 864 // Due to stret, the lowered function could have arguments. Just create the 865 // same type as was lowered by ConvertType but strip off the varargs bit. 866 std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end()); 867 Ty = llvm::FunctionType::get(Ty->getReturnType(), Args, false); 868 } 869 870 // Get or create the prototype for teh function. 871 llvm::Constant *Entry = GetAddrOfFunction(D, Ty); 872 873 // Strip off a bitcast if we got one back. 874 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 875 assert(CE->getOpcode() == llvm::Instruction::BitCast); 876 Entry = CE->getOperand(0); 877 } 878 879 880 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) { 881 // If the types mismatch then we have to rewrite the definition. 882 assert(cast<llvm::GlobalValue>(Entry)->isDeclaration() && 883 "Shouldn't replace non-declaration"); 884 885 // F is the Function* for the one with the wrong type, we must make a new 886 // Function* and update everything that used F (a declaration) with the new 887 // Function* (which will be a definition). 888 // 889 // This happens if there is a prototype for a function 890 // (e.g. "int f()") and then a definition of a different type 891 // (e.g. "int f(int x)"). Start by making a new function of the 892 // correct type, RAUW, then steal the name. 893 GlobalDeclMap.erase(getMangledName(D)); 894 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(D, Ty)); 895 NewFn->takeName(cast<llvm::GlobalValue>(Entry)); 896 897 // Replace uses of F with the Function we will endow with a body. 898 llvm::Constant *NewPtrForOldDecl = 899 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType()); 900 Entry->replaceAllUsesWith(NewPtrForOldDecl); 901 902 // Ok, delete the old function now, which is dead. 903 // FIXME: If it was attribute(used) the pointer will dangle from the 904 // LLVMUsed array! 905 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 906 907 Entry = NewFn; 908 } 909 910 llvm::Function *Fn = cast<llvm::Function>(Entry); 911 912 CodeGenFunction(*this).GenerateCode(D, Fn); 913 914 SetFunctionAttributesForDefinition(D, Fn); 915 916 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 917 AddGlobalCtor(Fn, CA->getPriority()); 918 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 919 AddGlobalDtor(Fn, DA->getPriority()); 920 } 921 922 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 923 // Make sure that this type is translated. 924 Types.UpdateCompletedType(TD); 925 } 926 927 928 /// getBuiltinLibFunction 929 llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 930 if (BuiltinID > BuiltinFunctions.size()) 931 BuiltinFunctions.resize(BuiltinID); 932 933 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 934 // a slot for it. 935 assert(BuiltinID && "Invalid Builtin ID"); 936 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 937 if (FunctionSlot) 938 return FunctionSlot; 939 940 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 941 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 942 "isn't a lib fn"); 943 944 // Get the name, skip over the __builtin_ prefix (if necessary). 945 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 946 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 947 Name += 10; 948 949 // Get the type for the builtin. 950 Builtin::Context::GetBuiltinTypeError Error; 951 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error); 952 assert(Error == Builtin::Context::GE_None && "Can't get builtin type"); 953 954 const llvm::FunctionType *Ty = 955 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 956 957 // FIXME: This has a serious problem with code like this: 958 // void abs() {} 959 // ... __builtin_abs(x); 960 // The two versions of abs will collide. The fix is for the builtin to win, 961 // and for the existing one to be turned into a constantexpr cast of the 962 // builtin. In the case where the existing one is a static function, it 963 // should just be renamed. 964 if (llvm::Function *Existing = getModule().getFunction(Name)) { 965 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 966 return FunctionSlot = Existing; 967 assert(Existing == 0 && "FIXME: Name collision"); 968 } 969 970 llvm::GlobalValue *&ExistingFn = 971 GlobalDeclMap[getContext().Idents.get(Name).getName()]; 972 assert(!ExistingFn && "Asking for the same builtin multiple times?"); 973 974 // FIXME: param attributes for sext/zext etc. 975 return FunctionSlot = ExistingFn = 976 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name, 977 &getModule()); 978 } 979 980 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 981 unsigned NumTys) { 982 return llvm::Intrinsic::getDeclaration(&getModule(), 983 (llvm::Intrinsic::ID)IID, Tys, NumTys); 984 } 985 986 llvm::Function *CodeGenModule::getMemCpyFn() { 987 if (MemCpyFn) return MemCpyFn; 988 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 989 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 990 } 991 992 llvm::Function *CodeGenModule::getMemMoveFn() { 993 if (MemMoveFn) return MemMoveFn; 994 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 995 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 996 } 997 998 llvm::Function *CodeGenModule::getMemSetFn() { 999 if (MemSetFn) return MemSetFn; 1000 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 1001 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 1002 } 1003 1004 static void appendFieldAndPadding(CodeGenModule &CGM, 1005 std::vector<llvm::Constant*>& Fields, 1006 FieldDecl *FieldD, FieldDecl *NextFieldD, 1007 llvm::Constant* Field, 1008 RecordDecl* RD, const llvm::StructType *STy) { 1009 // Append the field. 1010 Fields.push_back(Field); 1011 1012 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD); 1013 1014 int NextStructFieldNo; 1015 if (!NextFieldD) { 1016 NextStructFieldNo = STy->getNumElements(); 1017 } else { 1018 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD); 1019 } 1020 1021 // Append padding 1022 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) { 1023 llvm::Constant *C = 1024 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1)); 1025 1026 Fields.push_back(C); 1027 } 1028 } 1029 1030 // We still need to work out the details of handling UTF-16. 1031 // See: <rdr://2996215> 1032 llvm::Constant *CodeGenModule:: 1033 GetAddrOfConstantCFString(const std::string &str) { 1034 llvm::StringMapEntry<llvm::Constant *> &Entry = 1035 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1036 1037 if (Entry.getValue()) 1038 return Entry.getValue(); 1039 1040 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 1041 llvm::Constant *Zeros[] = { Zero, Zero }; 1042 1043 if (!CFConstantStringClassRef) { 1044 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1045 Ty = llvm::ArrayType::get(Ty, 0); 1046 1047 // FIXME: This is fairly broken if 1048 // __CFConstantStringClassReference is already defined, in that it 1049 // will get renamed and the user will most likely see an opaque 1050 // error message. This is a general issue with relying on 1051 // particular names. 1052 llvm::GlobalVariable *GV = 1053 new llvm::GlobalVariable(Ty, false, 1054 llvm::GlobalVariable::ExternalLinkage, 0, 1055 "__CFConstantStringClassReference", 1056 &getModule()); 1057 1058 // Decay array -> ptr 1059 CFConstantStringClassRef = 1060 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1061 } 1062 1063 QualType CFTy = getContext().getCFConstantStringType(); 1064 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl(); 1065 1066 const llvm::StructType *STy = 1067 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1068 1069 std::vector<llvm::Constant*> Fields; 1070 RecordDecl::field_iterator Field = CFRD->field_begin(); 1071 1072 // Class pointer. 1073 FieldDecl *CurField = *Field++; 1074 FieldDecl *NextField = *Field++; 1075 appendFieldAndPadding(*this, Fields, CurField, NextField, 1076 CFConstantStringClassRef, CFRD, STy); 1077 1078 // Flags. 1079 CurField = NextField; 1080 NextField = *Field++; 1081 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1082 appendFieldAndPadding(*this, Fields, CurField, NextField, 1083 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy); 1084 1085 // String pointer. 1086 CurField = NextField; 1087 NextField = *Field++; 1088 llvm::Constant *C = llvm::ConstantArray::get(str); 1089 C = new llvm::GlobalVariable(C->getType(), true, 1090 llvm::GlobalValue::InternalLinkage, 1091 C, ".str", &getModule()); 1092 appendFieldAndPadding(*this, Fields, CurField, NextField, 1093 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2), 1094 CFRD, STy); 1095 1096 // String length. 1097 CurField = NextField; 1098 NextField = 0; 1099 Ty = getTypes().ConvertType(getContext().LongTy); 1100 appendFieldAndPadding(*this, Fields, CurField, NextField, 1101 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy); 1102 1103 // The struct. 1104 C = llvm::ConstantStruct::get(STy, Fields); 1105 llvm::GlobalVariable *GV = 1106 new llvm::GlobalVariable(C->getType(), true, 1107 llvm::GlobalVariable::InternalLinkage, 1108 C, "", &getModule()); 1109 1110 GV->setSection("__DATA,__cfstring"); 1111 Entry.setValue(GV); 1112 1113 return GV; 1114 } 1115 1116 /// GetStringForStringLiteral - Return the appropriate bytes for a 1117 /// string literal, properly padded to match the literal type. 1118 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1119 const char *StrData = E->getStrData(); 1120 unsigned Len = E->getByteLength(); 1121 1122 const ConstantArrayType *CAT = 1123 getContext().getAsConstantArrayType(E->getType()); 1124 assert(CAT && "String isn't pointer or array!"); 1125 1126 // Resize the string to the right size. 1127 std::string Str(StrData, StrData+Len); 1128 uint64_t RealLen = CAT->getSize().getZExtValue(); 1129 1130 if (E->isWide()) 1131 RealLen *= getContext().Target.getWCharWidth()/8; 1132 1133 Str.resize(RealLen, '\0'); 1134 1135 return Str; 1136 } 1137 1138 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1139 /// constant array for the given string literal. 1140 llvm::Constant * 1141 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1142 // FIXME: This can be more efficient. 1143 return GetAddrOfConstantString(GetStringForStringLiteral(S)); 1144 } 1145 1146 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1147 /// array for the given ObjCEncodeExpr node. 1148 llvm::Constant * 1149 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1150 std::string Str; 1151 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1152 1153 return GetAddrOfConstantCString(Str); 1154 } 1155 1156 1157 /// GenerateWritableString -- Creates storage for a string literal. 1158 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1159 bool constant, 1160 CodeGenModule &CGM, 1161 const char *GlobalName) { 1162 // Create Constant for this string literal. Don't add a '\0'. 1163 llvm::Constant *C = llvm::ConstantArray::get(str, false); 1164 1165 // Create a global variable for this string 1166 return new llvm::GlobalVariable(C->getType(), constant, 1167 llvm::GlobalValue::InternalLinkage, 1168 C, GlobalName ? GlobalName : ".str", 1169 &CGM.getModule()); 1170 } 1171 1172 /// GetAddrOfConstantString - Returns a pointer to a character array 1173 /// containing the literal. This contents are exactly that of the 1174 /// given string, i.e. it will not be null terminated automatically; 1175 /// see GetAddrOfConstantCString. Note that whether the result is 1176 /// actually a pointer to an LLVM constant depends on 1177 /// Feature.WriteableStrings. 1178 /// 1179 /// The result has pointer to array type. 1180 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1181 const char *GlobalName) { 1182 // Don't share any string literals if writable-strings is turned on. 1183 if (Features.WritableStrings) 1184 return GenerateStringLiteral(str, false, *this, GlobalName); 1185 1186 llvm::StringMapEntry<llvm::Constant *> &Entry = 1187 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1188 1189 if (Entry.getValue()) 1190 return Entry.getValue(); 1191 1192 // Create a global variable for this. 1193 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1194 Entry.setValue(C); 1195 return C; 1196 } 1197 1198 /// GetAddrOfConstantCString - Returns a pointer to a character 1199 /// array containing the literal and a terminating '\-' 1200 /// character. The result has pointer to array type. 1201 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1202 const char *GlobalName){ 1203 return GetAddrOfConstantString(str + '\0', GlobalName); 1204 } 1205 1206 /// EmitObjCPropertyImplementations - Emit information for synthesized 1207 /// properties for an implementation. 1208 void CodeGenModule::EmitObjCPropertyImplementations(const 1209 ObjCImplementationDecl *D) { 1210 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(), 1211 e = D->propimpl_end(); i != e; ++i) { 1212 ObjCPropertyImplDecl *PID = *i; 1213 1214 // Dynamic is just for type-checking. 1215 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1216 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1217 1218 // Determine which methods need to be implemented, some may have 1219 // been overridden. Note that ::isSynthesized is not the method 1220 // we want, that just indicates if the decl came from a 1221 // property. What we want to know is if the method is defined in 1222 // this implementation. 1223 if (!D->getInstanceMethod(PD->getGetterName())) 1224 CodeGenFunction(*this).GenerateObjCGetter( 1225 const_cast<ObjCImplementationDecl *>(D), PID); 1226 if (!PD->isReadOnly() && 1227 !D->getInstanceMethod(PD->getSetterName())) 1228 CodeGenFunction(*this).GenerateObjCSetter( 1229 const_cast<ObjCImplementationDecl *>(D), PID); 1230 } 1231 } 1232 } 1233 1234 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1235 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1236 // If an error has occurred, stop code generation, but continue 1237 // parsing and semantic analysis (to ensure all warnings and errors 1238 // are emitted). 1239 if (Diags.hasErrorOccurred()) 1240 return; 1241 1242 switch (D->getKind()) { 1243 case Decl::Function: 1244 case Decl::Var: 1245 EmitGlobal(cast<ValueDecl>(D)); 1246 break; 1247 1248 case Decl::Namespace: 1249 ErrorUnsupported(D, "namespace"); 1250 break; 1251 1252 // Objective-C Decls 1253 1254 // Forward declarations, no (immediate) code generation. 1255 case Decl::ObjCClass: 1256 case Decl::ObjCForwardProtocol: 1257 case Decl::ObjCCategory: 1258 case Decl::ObjCInterface: 1259 break; 1260 1261 case Decl::ObjCProtocol: 1262 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1263 break; 1264 1265 case Decl::ObjCCategoryImpl: 1266 // Categories have properties but don't support synthesize so we 1267 // can ignore them here. 1268 1269 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1270 break; 1271 1272 case Decl::ObjCImplementation: { 1273 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1274 EmitObjCPropertyImplementations(OMD); 1275 Runtime->GenerateClass(OMD); 1276 break; 1277 } 1278 case Decl::ObjCMethod: { 1279 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1280 // If this is not a prototype, emit the body. 1281 if (OMD->getBody()) 1282 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1283 break; 1284 } 1285 case Decl::ObjCCompatibleAlias: 1286 // compatibility-alias is a directive and has no code gen. 1287 break; 1288 1289 case Decl::LinkageSpec: { 1290 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D); 1291 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx) 1292 ErrorUnsupported(LSD, "linkage spec"); 1293 // FIXME: implement C++ linkage, C linkage works mostly by C 1294 // language reuse already. 1295 break; 1296 } 1297 1298 case Decl::FileScopeAsm: { 1299 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1300 std::string AsmString(AD->getAsmString()->getStrData(), 1301 AD->getAsmString()->getByteLength()); 1302 1303 const std::string &S = getModule().getModuleInlineAsm(); 1304 if (S.empty()) 1305 getModule().setModuleInlineAsm(AsmString); 1306 else 1307 getModule().setModuleInlineAsm(S + '\n' + AsmString); 1308 break; 1309 } 1310 1311 default: 1312 // Make sure we handled everything we should, every other kind is 1313 // a non-top-level decl. FIXME: Would be nice to have an 1314 // isTopLevelDeclKind function. Need to recode Decl::Kind to do 1315 // that easily. 1316 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1317 } 1318 } 1319