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 "CodeGenFunction.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/Basic/Diagnostic.h" 19 #include "clang/Basic/LangOptions.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "llvm/CallingConv.h" 22 #include "llvm/Constants.h" 23 #include "llvm/DerivedTypes.h" 24 #include "llvm/Module.h" 25 #include "llvm/Intrinsics.h" 26 #include <algorithm> 27 using namespace clang; 28 using namespace CodeGen; 29 30 31 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 32 llvm::Module &M, const llvm::TargetData &TD, 33 Diagnostic &diags) 34 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags), 35 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) { 36 //TODO: Make this selectable at runtime 37 Runtime = CreateObjCRuntime(M, 38 getTypes().ConvertType(getContext().IntTy), 39 getTypes().ConvertType(getContext().LongTy)); 40 } 41 42 CodeGenModule::~CodeGenModule() { 43 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction(); 44 if (ObjCInitFunction) 45 AddGlobalCtor(ObjCInitFunction); 46 EmitGlobalCtors(); 47 delete Runtime; 48 } 49 50 /// WarnUnsupported - Print out a warning that codegen doesn't support the 51 /// specified stmt yet. 52 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) { 53 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 54 "cannot codegen this %0 yet"); 55 SourceRange Range = S->getSourceRange(); 56 std::string Msg = Type; 57 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID, 58 &Msg, 1, &Range, 1); 59 } 60 61 /// WarnUnsupported - Print out a warning that codegen doesn't support the 62 /// specified decl yet. 63 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) { 64 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 65 "cannot codegen this %0 yet"); 66 std::string Msg = Type; 67 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID, 68 &Msg, 1); 69 } 70 71 /// AddGlobalCtor - Add a function to the list that will be called before 72 /// main() runs. 73 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) { 74 // TODO: Type coercion of void()* types. 75 GlobalCtors.push_back(Ctor); 76 } 77 78 /// EmitGlobalCtors - Generates the array of contsturctor functions to be 79 /// called on module load, if any have been registered with AddGlobalCtor. 80 void CodeGenModule::EmitGlobalCtors() { 81 if (GlobalCtors.empty()) return; 82 83 // Get the type of @llvm.global_ctors 84 std::vector<const llvm::Type*> CtorFields; 85 CtorFields.push_back(llvm::IntegerType::get(32)); 86 // Constructor function type 87 std::vector<const llvm::Type*> VoidArgs; 88 llvm::FunctionType* CtorFuncTy = 89 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false); 90 91 // i32, function type pair 92 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy); 93 llvm::StructType* CtorStructTy = 94 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL); 95 // Array of fields 96 llvm::ArrayType* GlobalCtorsTy = 97 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size()); 98 99 // Define the global variable 100 llvm::GlobalVariable *GlobalCtorsVal = 101 new llvm::GlobalVariable(GlobalCtorsTy, false, 102 llvm::GlobalValue::AppendingLinkage, 103 (llvm::Constant*)0, "llvm.global_ctors", 104 &TheModule); 105 106 // Populate the array 107 std::vector<llvm::Constant*> CtorValues; 108 llvm::Constant *MagicNumber = 109 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false); 110 std::vector<llvm::Constant*> StructValues; 111 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(), 112 E = GlobalCtors.end(); I != E; ++I) { 113 StructValues.clear(); 114 StructValues.push_back(MagicNumber); 115 StructValues.push_back(*I); 116 117 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues)); 118 } 119 120 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy, 121 CtorValues)); 122 } 123 124 125 126 /// ReplaceMapValuesWith - This is a really slow and bad function that 127 /// searches for any entries in GlobalDeclMap that point to OldVal, changing 128 /// them to point to NewVal. This is badbadbad, FIXME! 129 void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal, 130 llvm::Constant *NewVal) { 131 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator 132 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I) 133 if (I->second == OldVal) I->second = NewVal; 134 } 135 136 137 llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D, 138 bool isDefinition) { 139 // See if it is already in the map. If so, just return it. 140 llvm::Constant *&Entry = GlobalDeclMap[D]; 141 if (Entry) return Entry; 142 143 const llvm::Type *Ty = getTypes().ConvertType(D->getType()); 144 145 // Check to see if the function already exists. 146 llvm::Function *F = getModule().getFunction(D->getName()); 147 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); 148 149 // If it doesn't already exist, just create and return an entry. 150 if (F == 0) { 151 // FIXME: param attributes for sext/zext etc. 152 F = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(), 153 &getModule()); 154 155 // Set the appropriate calling convention for the Function. 156 if (D->getAttr<FastCallAttr>()) 157 F->setCallingConv(llvm::CallingConv::Fast); 158 return Entry = F; 159 } 160 161 // If the pointer type matches, just return it. 162 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty); 163 if (PFTy == F->getType()) return Entry = F; 164 165 // If this isn't a definition, just return it casted to the right type. 166 if (!isDefinition) 167 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy); 168 169 // Otherwise, we have a definition after a prototype with the wrong type. 170 // F is the Function* for the one with the wrong type, we must make a new 171 // Function* and update everything that used F (a declaration) with the new 172 // Function* (which will be a definition). 173 // 174 // This happens if there is a prototype for a function (e.g. "int f()") and 175 // then a definition of a different type (e.g. "int f(int x)"). Start by 176 // making a new function of the correct type, RAUW, then steal the name. 177 llvm::Function *NewFn = new llvm::Function(FTy, 178 llvm::Function::ExternalLinkage, 179 "", &getModule()); 180 NewFn->takeName(F); 181 182 // Replace uses of F with the Function we will endow with a body. 183 llvm::Constant *NewPtrForOldDecl = 184 llvm::ConstantExpr::getBitCast(NewFn, F->getType()); 185 F->replaceAllUsesWith(NewPtrForOldDecl); 186 187 // FIXME: Update the globaldeclmap for the previous decl of this name. We 188 // really want a way to walk all of these, but we don't have it yet. This 189 // is incredibly slow! 190 ReplaceMapValuesWith(F, NewPtrForOldDecl); 191 192 // Ok, delete the old function now, which is dead. 193 assert(F->isDeclaration() && "Shouldn't replace non-declaration"); 194 F->eraseFromParent(); 195 196 // Return the new function which has the right type. 197 return Entry = NewFn; 198 } 199 200 static bool IsZeroElementArray(const llvm::Type *Ty) { 201 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty)) 202 return ATy->getNumElements() == 0; 203 return false; 204 } 205 206 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 207 bool isDefinition) { 208 assert(D->hasGlobalStorage() && "Not a global variable"); 209 210 // See if it is already in the map. 211 llvm::Constant *&Entry = GlobalDeclMap[D]; 212 if (Entry) return Entry; 213 214 QualType ASTTy = D->getType(); 215 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 216 217 // Check to see if the global already exists. 218 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true); 219 220 // If it doesn't already exist, just create and return an entry. 221 if (GV == 0) { 222 return Entry = new llvm::GlobalVariable(Ty, false, 223 llvm::GlobalValue::ExternalLinkage, 224 0, D->getName(), &getModule(), 0, 225 ASTTy.getAddressSpace()); 226 } 227 228 // If the pointer type matches, just return it. 229 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 230 if (PTy == GV->getType()) return Entry = GV; 231 232 // If this isn't a definition, just return it casted to the right type. 233 if (!isDefinition) 234 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy); 235 236 237 // Otherwise, we have a definition after a prototype with the wrong type. 238 // GV is the GlobalVariable* for the one with the wrong type, we must make a 239 /// new GlobalVariable* and update everything that used GV (a declaration) 240 // with the new GlobalVariable* (which will be a definition). 241 // 242 // This happens if there is a prototype for a global (e.g. "extern int x[];") 243 // and then a definition of a different type (e.g. "int x[10];"). Start by 244 // making a new global of the correct type, RAUW, then steal the name. 245 llvm::GlobalVariable *NewGV = 246 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage, 247 0, D->getName(), &getModule(), 0, 248 ASTTy.getAddressSpace()); 249 NewGV->takeName(GV); 250 251 // Replace uses of GV with the globalvalue we will endow with a body. 252 llvm::Constant *NewPtrForOldDecl = 253 llvm::ConstantExpr::getBitCast(NewGV, GV->getType()); 254 GV->replaceAllUsesWith(NewPtrForOldDecl); 255 256 // FIXME: Update the globaldeclmap for the previous decl of this name. We 257 // really want a way to walk all of these, but we don't have it yet. This 258 // is incredibly slow! 259 ReplaceMapValuesWith(GV, NewPtrForOldDecl); 260 261 // Verify that GV was a declaration or something like x[] which turns into 262 // [0 x type]. 263 assert((GV->isDeclaration() || 264 IsZeroElementArray(GV->getType()->getElementType())) && 265 "Shouldn't replace non-declaration"); 266 267 // Ok, delete the old global now, which is dead. 268 GV->eraseFromParent(); 269 270 // Return the new global which has the right type. 271 return Entry = NewGV; 272 } 273 274 275 void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) { 276 // If this is not a prototype, emit the body. 277 if (OMD->getBody()) 278 CodeGenFunction(*this).GenerateObjCMethod(OMD); 279 } 280 281 void CodeGenModule::EmitFunction(const FunctionDecl *FD) { 282 // If this is not a prototype, emit the body. 283 if (FD->getBody()) 284 CodeGenFunction(*this).GenerateCode(FD); 285 } 286 287 llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) { 288 return EmitConstantExpr(Expr); 289 } 290 291 void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) { 292 // If this is just a forward declaration of the variable, don't emit it now, 293 // allow it to be emitted lazily on its first use. 294 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0) 295 return; 296 297 // Get the global, forcing it to be a direct reference. 298 llvm::GlobalVariable *GV = 299 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true)); 300 301 // Convert the initializer, or use zero if appropriate. 302 llvm::Constant *Init = 0; 303 if (D->getInit() == 0) { 304 Init = llvm::Constant::getNullValue(GV->getType()->getElementType()); 305 } else if (D->getType()->isIntegerType()) { 306 llvm::APSInt Value(static_cast<uint32_t>( 307 getContext().getTypeSize(D->getInit()->getType()))); 308 if (D->getInit()->isIntegerConstantExpr(Value, Context)) 309 Init = llvm::ConstantInt::get(Value); 310 } 311 312 if (!Init) 313 Init = EmitGlobalInit(D->getInit()); 314 315 assert(GV->getType()->getElementType() == Init->getType() && 316 "Initializer codegen type mismatch!"); 317 GV->setInitializer(Init); 318 319 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 320 GV->setVisibility(attr->getVisibility()); 321 // FIXME: else handle -fvisibility 322 323 // Set the llvm linkage type as appropriate. 324 if (D->getAttr<DLLImportAttr>()) 325 GV->setLinkage(llvm::Function::DLLImportLinkage); 326 else if (D->getAttr<DLLExportAttr>()) 327 GV->setLinkage(llvm::Function::DLLExportLinkage); 328 else if (D->getAttr<WeakAttr>()) { 329 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 330 331 } else { 332 // FIXME: This isn't right. This should handle common linkage and other 333 // stuff. 334 switch (D->getStorageClass()) { 335 case VarDecl::Auto: 336 case VarDecl::Register: 337 assert(0 && "Can't have auto or register globals"); 338 case VarDecl::None: 339 if (!D->getInit()) 340 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 341 break; 342 case VarDecl::Extern: 343 case VarDecl::PrivateExtern: 344 // todo: common 345 break; 346 case VarDecl::Static: 347 GV->setLinkage(llvm::GlobalVariable::InternalLinkage); 348 break; 349 } 350 } 351 } 352 353 /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified 354 /// declarator chain. 355 void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) { 356 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator())) 357 EmitGlobalVar(D); 358 } 359 360 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 361 // Make sure that this type is translated. 362 Types.UpdateCompletedType(TD); 363 } 364 365 366 /// getBuiltinLibFunction 367 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 368 if (BuiltinID > BuiltinFunctions.size()) 369 BuiltinFunctions.resize(BuiltinID); 370 371 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 372 // a slot for it. 373 assert(BuiltinID && "Invalid Builtin ID"); 374 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 375 if (FunctionSlot) 376 return FunctionSlot; 377 378 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn"); 379 380 // Get the name, skip over the __builtin_ prefix. 381 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10; 382 383 // Get the type for the builtin. 384 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context); 385 const llvm::FunctionType *Ty = 386 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 387 388 // FIXME: This has a serious problem with code like this: 389 // void abs() {} 390 // ... __builtin_abs(x); 391 // The two versions of abs will collide. The fix is for the builtin to win, 392 // and for the existing one to be turned into a constantexpr cast of the 393 // builtin. In the case where the existing one is a static function, it 394 // should just be renamed. 395 if (llvm::Function *Existing = getModule().getFunction(Name)) { 396 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 397 return FunctionSlot = Existing; 398 assert(Existing == 0 && "FIXME: Name collision"); 399 } 400 401 // FIXME: param attributes for sext/zext etc. 402 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage, 403 Name, &getModule()); 404 } 405 406 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 407 unsigned NumTys) { 408 return llvm::Intrinsic::getDeclaration(&getModule(), 409 (llvm::Intrinsic::ID)IID, Tys, NumTys); 410 } 411 412 llvm::Function *CodeGenModule::getMemCpyFn() { 413 if (MemCpyFn) return MemCpyFn; 414 llvm::Intrinsic::ID IID; 415 switch (Context.Target.getPointerWidth(0)) { 416 default: assert(0 && "Unknown ptr width"); 417 case 32: IID = llvm::Intrinsic::memcpy_i32; break; 418 case 64: IID = llvm::Intrinsic::memcpy_i64; break; 419 } 420 return MemCpyFn = getIntrinsic(IID); 421 } 422 423 llvm::Function *CodeGenModule::getMemSetFn() { 424 if (MemSetFn) return MemSetFn; 425 llvm::Intrinsic::ID IID; 426 switch (Context.Target.getPointerWidth(0)) { 427 default: assert(0 && "Unknown ptr width"); 428 case 32: IID = llvm::Intrinsic::memset_i32; break; 429 case 64: IID = llvm::Intrinsic::memset_i64; break; 430 } 431 return MemSetFn = getIntrinsic(IID); 432 } 433 434 llvm::Constant *CodeGenModule:: 435 GetAddrOfConstantCFString(const std::string &str) { 436 llvm::StringMapEntry<llvm::Constant *> &Entry = 437 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 438 439 if (Entry.getValue()) 440 return Entry.getValue(); 441 442 std::vector<llvm::Constant*> Fields; 443 444 if (!CFConstantStringClassRef) { 445 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 446 Ty = llvm::ArrayType::get(Ty, 0); 447 448 CFConstantStringClassRef = 449 new llvm::GlobalVariable(Ty, false, 450 llvm::GlobalVariable::ExternalLinkage, 0, 451 "__CFConstantStringClassReference", 452 &getModule()); 453 } 454 455 // Class pointer. 456 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 457 llvm::Constant *Zeros[] = { Zero, Zero }; 458 llvm::Constant *C = 459 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2); 460 Fields.push_back(C); 461 462 // Flags. 463 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 464 Fields.push_back(llvm::ConstantInt::get(Ty, 1992)); 465 466 // String pointer. 467 C = llvm::ConstantArray::get(str); 468 C = new llvm::GlobalVariable(C->getType(), true, 469 llvm::GlobalValue::InternalLinkage, 470 C, ".str", &getModule()); 471 472 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); 473 Fields.push_back(C); 474 475 // String length. 476 Ty = getTypes().ConvertType(getContext().LongTy); 477 Fields.push_back(llvm::ConstantInt::get(Ty, str.length())); 478 479 // The struct. 480 Ty = getTypes().ConvertType(getContext().getCFConstantStringType()); 481 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields); 482 llvm::GlobalVariable *GV = 483 new llvm::GlobalVariable(C->getType(), true, 484 llvm::GlobalVariable::InternalLinkage, 485 C, "", &getModule()); 486 GV->setSection("__DATA,__cfstring"); 487 Entry.setValue(GV); 488 return GV; 489 } 490 491 /// GenerateWritableString -- Creates storage for a string literal. 492 static llvm::Constant *GenerateStringLiteral(const std::string &str, 493 bool constant, 494 CodeGenModule &CGM) { 495 // Create Constant for this string literal 496 llvm::Constant *C=llvm::ConstantArray::get(str); 497 498 // Create a global variable for this string 499 C = new llvm::GlobalVariable(C->getType(), constant, 500 llvm::GlobalValue::InternalLinkage, 501 C, ".str", &CGM.getModule()); 502 return C; 503 } 504 505 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character 506 /// array containing the literal. The result is pointer to array type. 507 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) { 508 // Don't share any string literals if writable-strings is turned on. 509 if (Features.WritableStrings) 510 return GenerateStringLiteral(str, false, *this); 511 512 llvm::StringMapEntry<llvm::Constant *> &Entry = 513 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 514 515 if (Entry.getValue()) 516 return Entry.getValue(); 517 518 // Create a global variable for this. 519 llvm::Constant *C = GenerateStringLiteral(str, true, *this); 520 Entry.setValue(C); 521 return C; 522 } 523